如在OC中使用AFNetworking一般,Swift我們用Alamofire來做網(wǎng)絡(luò)庫(kù).而Moya在Alamofire的基礎(chǔ)上又封裝了一層:
官方介紹里說Moya有幾個(gè)比較好的特性:
- 編譯時(shí)檢查正確的API端點(diǎn)訪問.
- 使你定義不同端點(diǎn)枚舉值對(duì)應(yīng)相應(yīng)的用途更加明晰.
- 提高測(cè)試地位從而使單元測(cè)試更加容易.
Moya已經(jīng)在Artsy's new auction app上使用,可以下載代碼來看看.
不過官方還有個(gè)例子文檔,大致內(nèi)容為:
首先定義個(gè)借口地址的枚舉:
enum GitHub {
case Zen
case UserProfile(String)
}
這個(gè)枚舉需要遵守MoyaTarget
協(xié)議:
private extension String {
var URLEscapedString: String {
return self.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet())
}
}
private extension String {
var URLEscapedString: String {
return self.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet())
}
}
extension GitHub : MoyaTarget {
var baseURL: NSURL { return NSURL(string: "https://api.github.com") }
var path: String {
switch self {
case .Zen:
return "/zen"
case .UserProfile(let name):
return "/users/\(name.URLEscapedString)"
}
}
var method: Moya.Method {
return .GET
}
var parameters: [String: AnyObject]? {
return nil
}
var sampleData: NSData {
switch self {
case .Zen:
return "Half measures are as bad as nothing at all.".dataUsingEncoding(NSUTF8StringEncoding)!
case .UserProfile(let name):
return "{\"login\": \"\(name)\", \"id\": 100}".dataUsingEncoding(NSUTF8StringEncoding)!
}
}
}
設(shè)置好基礎(chǔ)url、參數(shù)、方法等,接下來設(shè)置最終的API地址:
public func url(route: MoyaTarget) -> String {
return route.baseURL.URLByAppendingPathComponent(route.path).absoluteString
}
let endpointClosure = { (target: GitHub, method: Moya.Method, parameters: [String: AnyObject]) -> Endpoint<GitHub> in
return Endpoint<GitHub>(URL: url(target), method: method, parameters: parameters, sampleResponseClosure: {.NetworkResponse(200, target.sampleData)})
}
可以設(shè)置網(wǎng)絡(luò)錯(cuò)誤或超時(shí)的情況:
let failureEndpointClosure = { (target: GitHub, method: Moya.Method, parameters: [String: AnyObject]) -> Endpoint<GitHub> in
let sampleResponseClosure = { () -> (EndpointSampleResponse) in
if shouldTimeout {
return .NetworkError(NSError())
} else {
return .NetworkResponse(200, target.sampleData)
}
}()
return Endpoint<GitHub>(URL: url(target), method: method, parameters: parameters, sampleResponseClosure: sampleResponseClosure)
}
接下來創(chuàng)建我們需要的網(wǎng)絡(luò)層:
// Tuck this away somewhere where it'll be visible to anyone who wants to use it
var provider: MoyaProvider<GitHub>!
// Create this instance at app launch
let provider = MoyaProvider(endpointClosure: endpointClosure)
我們調(diào)用時(shí)非常簡(jiǎn)單:
provider.request(.Zen, completion: { (data, statusCode, response, error) in
if let data = data {
// do something with the data
}
})
Girl學(xué)iOS100天 第7天