Alamofire
Alamofire是目前为止我接触的swift最好的第三方下载库,它根本就不需要另外封装,所有的下载方法都是class func。同时呢,它提供了很多种回调的方法:
//最简单下载
Alamofire.request(.GET, "https://httpbin.org/get")
//带参数
Alamofire.request(.GET, "https://httpbin.org/get", parameters: ["foo": "bar"]).response { (request, response, data, error) in})
//URL转码
Alamofire.request(Method.GET, "https://httpbin.org/get", parameters: nil, encoding: ParameterEncoding.URL,headers: nil).responseString { (response) in})另外它的返回值有很多种,比如response、responseJSON、responseString等闭包。我自己最喜欢用的就是responseString。这里呢,也普及一下responseString返回对象都有哪些属性:
//response闭包,它包含返回的result与是否正确的bool状态print("response:- \(response)")
//请求相关的东西,打印出一个可选型的URLprint("request:-\(response.request)")
//包含有可选型的URL、状态、请求头;请求头里有日期大小等print("response:-\(response.response)")
//打印出的二进制print("data:-\(response.data)")
//打印时间相关print("time:-\(response.timeline.totalDuration)")所以我们最终需要的就只是result.value。
而有时候我们是需要返回进度的东西,有一点需要注意的是进度闭包不是在主线程的,所以要使用进度的时候要把它放到主线程里。
public func progress(closure: ((Int64, Int64, Int64) -> Void)? = nil) -> Self {}下载还有一个经常用到的就是时间控制了,这个东西很坑的一点就是网上很多加时间限制的方法是错误的。因为时间限制是加在URLSession上的confige上的。
把以上几点综合一下,我封装了一个下载的函数: