如在OC中使用AFNetworking一般,Swift我们用Alamofire来做网络库.而Moya在Alamofire的基础上又封装了一层:
官方介绍里说Moya有几个比较好的特性:
- 编译时检查正确的API端点访问.
- 使你定义不同端点枚举值对应相应的用途更加明晰.
- 提高测试地位从而使单元测试更加容易.
Moya已经在Artsy's new auction app上使用,可以下载代码来看看.
不过官方还有个例子文档,大致内容为:
首先定义个借口地址的枚举:
enum GitHub {
case Zen
case UserProfile(String)
}
这个枚举需要遵守MoyaTarget
协议:
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)!
}
}
}
设置好基础url、参数、方法等,接下来设置最终的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)})
}
可以设置网络错误或超时的情况:
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)
}
接下来创建我们需要的网络层:
// 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)
我们调用时非常简单:
provider.request(.Zen, completion: { (data, statusCode, response, error) in
if let data = data {
// do something with the data
}
})
Girl学iOS100天 第7天