天天看點

每個ios開發者都應該知道Top 10 Swift三方庫

原文:Top 10 iOS Swift libraries every iOS developer should know about

swift每天都在變的越來越流行。如果你正開始一個新項目,你有機會決定使用swift。為了你轉變(從ios轉swift)更容易和節省你造輪子的時間,下面是我們認為每個ios開發者都應該知道的10個三方庫。

就像我們在Top 5 iOS libraries every iOS developer should know about這篇文章提到的一樣,Github和Bitbucker是發現開源庫的好地方,像CocoaPods和Carthage這樣的工具可以幫你快速安裝和管理你項目中的三方庫,讓你管理依賴更簡單。

每個ios開發者都應該知道Top 10 Swift三方庫

1.Alamofire

當你想要抽象簡化App中的網絡請求時,Alamofire是你需要的,Alamofire是一個Http網絡請求庫,建構在NSURLSession和基礎URL加載系統之上,它用簡單優雅的接口很好的封裝了網絡請求。

// Making a GET request
Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"])
         .responseJSON { response in
             print(response.request)  // original URL request
             print(response.response) // URL response
             print(response.data)     // server data
             print(response.result)   // result of response serialization

             if let JSON = response.result.value {
                 print("JSON: \(JSON)")
             }
         }
           

2.SwiftyJSON

swift的Explicit types(顯示類型)可以確定我們不會在代碼中犯錯和出現bug。但是有時處理起來還是比較麻煩,特别是和JSON打交道的時候。幸運的是,SwiftyJSON提供了可讀性更好的方式幫我們處理JSON資料。還提供了可選的自動解析!

// Typical JSON handling

if let statusesArray = try? NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments) as? [[String: AnyObject]],
    let user = statusesArray[0]["user"] as? [String: AnyObject],
    let username = user["name"] as? String {
    // Finally we got the username
}

// With SwiftyJSON

let json = JSON(data: dataFromNetworking)
if let userName = json[0]["user"]["name"].string {
  //Now you got your value
}
           

SwiftyJson也可以很好的和Alamofire配合使用。

Alamofire.request(.GET, url).validate().responseJSON { response in
    switch response.result {
    case .Success:
        if let value = response.result.value {
          let json = JSON(value)
          print("JSON: \(json)")
        }
    case .Failure(let error):
        print(error)
    }
}
           

3.ObjectMapper

如果你寫過一個通過API擷取資訊的app,你可能需要花大量時間寫代碼把你的響應結果映射為你的object。ObjectMapper可以幫你把JSON格式響應結果轉換成你的model對象,反之亦然。換句話說,它幫你把JSON映射成對象,也可以把對象轉換成JSON。嵌套的對象也支援。

// Temperature class that conforms to Mappable protocol

struct Temperature: Mappable {
    var celsius: Double?
    var fahrenheit: Double?

    init?(_ map: Map) {

    }

    mutating func mapping(map: Map) {
        celsius      map["celsius"]
        fahrenheit   map["fahrenheit"]
    }
}
           

AlamofireObjectMapper也值得提一下,一個Alamofire的擴充使用ObjectMapper将JSON響應資料轉換成swift對象。

4.Quick

Quick是一個行為驅動(BDD)開發架構,它的靈感來自于

RSpec,Specta, 和Ginkgo。配合Nimble一起使用,Nimble是一個測試比對架構。

// Documentation directory spec

class TableOfContentsSpec: QuickSpec {
  override func spec() {
    describe("the 'Documentation' directory") {
      it("has everything you need to get started") {
        let sections = Directory("Documentation").sections
        expect(sections).to(contain("Organized Tests with Quick Examples and Example Groups"))
        expect(sections).to(contain("Installing Quick"))
      }

      context("if it doesn't have what you're looking for") {
        it("needs to be updated") {
          let you = You(awesome: true)
          expect{you.submittedAnIssue}.toEventually(beTruthy())
        }
      }
    }
  }
}
           

5.Eureka

Eureka可以幫你簡單優雅的實作動态table-view表單。它由rows,sections和forms組成。如果你的app包含大量表單,Eureka可以真正幫你節省時間。

// Creating a form

class CustomCellsController : FormViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        form +++ Section("Custom cells")
                    <<< WeekDayRow(){
                        $0.value = [.Monday, .Wednesday, .Friday]
                    }
                    <<< TextFloatLabelRow() {
                        $0.title = "Float Label Row, type something to see.."
                    }
    }
}
           

6.RxSwift

RxSwift是一個基于Swift的的函數式響應程式設計架構。更具體點,RxSwift是是Rx的一個Swift語言版本(還有java版本RxJava,js->RxJs)它的目标是讓異步和事件資料流操作更簡單。KVO observing, async operations and delegates are all unified under abstraction of sequence(還沒來的及學習掩面哭),如果你已經使用過ReactiveCocoa,你接受起來會比較簡單(都是函數式程式設計思想)

// Combine first and last name sequences, and bind the resulting string to label

combineLatest(firstName.rx_text, lastName.rx_text) { $0 + " " + $1 }
            .map { "Greeting \($0)" }
            .bindTo(greetingLabel.rx_text)
           

7.SnapKit

SnapKit是一個用少量代碼寫出不丢可讀性auto layout的AutoLayout庫。

// Resizing and centering subview in its superview

let box = UIView()
let container = UIView()

container.addSubview(box)

box.snp_makeConstraints { (make) 
 Void in
    make.size.equalTo(50)
    make.center.equalTo(container)
}
           

8.Spring

Spring是一個可以幫你用代碼或者直接在Storybard建立動畫的動畫庫,在Storyboard你可以用runtime(通過設定IBInspectable屬性)來建立動畫,Spring已經成長為一個全面發展的動畫庫 支援很多已經存在的動畫。

// Usage with code

layer.animation = "wobble"
layer.animate()
           

9.Kingfisher

Kingfisher是一個輕量的下載下傳和緩存網絡圖檔庫。下載下傳和緩存是異步進行操作,已經下載下傳好的圖檔會緩存在記憶體和本地,極大得提高app的體驗。

// Basic example of downloading and caching an image

imageView.kf_setImageWithURL(NSURL(string: "http://your_image_url.png")!)
           

10.CoreStore

CoreStore是一個基于Core Data的封裝庫。它的目标是安全優雅和Core Data進行互動。CoreStore的API提供了常用的有效的方法讓你和你的資料庫進行互動。

// Storing a person entity

CoreStore.beginAsynchronous { (transaction) 
 Void in
    let person = transaction.create(Into(MyPersonEntity))
    person.name = "John Smith"
    person.age = 42

    transaction.commit { (result) 
 Void in
        switch result {
            case .Success(let hasChanges): print("success!")
            case .Failure(let error): print(error)
        }
    }
}
           

你的看法呢

你不認同?一些其他的三方庫應該出現在這個清單?給我們留言讓我們知道你的想法!