iOS developiOS Development With SwiftSwift开发技巧

Moya

2015-11-03  本文已影响4792人  Girl_iOS

如在OC中使用AFNetworking一般,Swift我们用Alamofire来做网络库.而Moya在Alamofire的基础上又封装了一层:

Moya.png
官方介绍里说Moya有几个比较好的特性:
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天

上一篇下一篇

猜你喜欢

热点阅读