iOS软件开发iOS学习iOS程序猿

Alamofire学习小结(基本使用)

2016-11-16  本文已影响742人  AirChen

一 安装:

cocoapods的配置文件如下:(cocoapods需要更新版本,才支撑swift的第三方框架,更新的方法可以参考:CocoaPods1.1.1更新

Podfile:        

 source 'https://github.com/CocoaPods/Specs.git'        

 platform :ios, '10.0'        

 use_frameworks!                

 target '' do

pod 'Alamofire', '~> 4.0'

end

完成之后添加一下动态库,如下图:

 二 基础用法:

Response handler

Alamofire 的网络操作都是异步进行(用response handler)的,最基本的请求代码如下:

Alamofire.request("https://httpbin.org/get").responseJSON { response in

print(response.request)  // original URL request

print(response.response) // HTTP URL response

print(response.data)    // server data

print(response.result)  // result of response serialization

if let JSON = response.result.value {

print("JSON: \(JSON)")

}}

Alamofire 默认包含物种类型的response handlers:response responseString responseJSON responseData

两种高级的方式:

1.Chained Response Handlers(链式,注意:会访问服务器数据多次)

Alamofire.request("https://httpbin.org/get")

.responseString { response in

print("Response String: \(response.result.value)")

}

.responseJSON { response in

print("Response JSON: \(response.result.value)")

}

It is important to note that using multiple response handlers on the same Request requires the server data to be serialized multiple times. Once for each response handler.

2.Response Handler Queue(多线程)

Response handlers 默认是在主线程上运行的,可以添加到GCD队列中。

let utilityQueue = DispatchQueue.global(qos: .utility)

Alamofire.request("https://httpbin.org/get").responseJSON(queue: utilityQueue) { response in

print("Executing response handler on utility queue")

}

判断服务器返回的数据有效性的方式:

Manual Validation

Alamofire.request("https://httpbin.org/get")

.validate(statusCode: 200..<300)

.validate(contentType: ["application/json"])

.responseData { response in

switch response.result {

case .success:

print("Validation Successful")

case .failure(let error):

print(error)

}}

Automatic Validation

Automatically validates status code within 200...299 range, and that the Content-Type header of the response matches the Accept header of the request, if one is provided.

Alamofire.request("https://httpbin.org/get").validate().responseJSON { response in

switch response.result {

case .success:

print("Validation Successful")

case .failure(let error):

print(error)

}}

 三 HTTP相关:

 HTTP Methods

public enum HTTPMethod: String {

case options = "OPTIONS"

case get    = "GET"

case head    = "HEAD"

case post    = "POST"

case put    = "PUT"

case patch  = "PATCH"

case delete  = "DELETE"

case trace  = "TRACE"

case connect = "CONNECT"

}

默认方法是 get

Alamofire.request("https://httpbin.org/post", method: .post)

Alamofire.request("https://httpbin.org/put", method: .put)

Alamofire.request("https://httpbin.org/delete", method: .delete)

Parameter Encoding(参数编码)

Alamofire 支持3种类型的参数编码:URL, JSON and PropertyList。也可以自定义类型,需支持ParameterEncoding协议。

 HTTP Headers(Http 头部)

let headers: HTTPHeaders = [

"Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",

"Accept": "application/json"

]

Alamofire.request("https://httpbin.org/headers", headers: headers).responseJSON { response in

debugPrint(response)

}

Alamofire SessionManager提供了默认的头部,内容如下:

• Accept-Encoding, which defaults to gzip;q=1.0, compress;q=0.5, per RFC 7230 §4.2.3.

• Accept-Language, which defaults to up to the top 6 preferred languages on the system, formatted like en;q=1.0, per RFC 7231 §5.3.5.

• User-Agent, which contains versioning information about the current app. For example: iOS Example/1.0 (com.alamofire.iOS-Example; build:1; iOS 10.0.0) Alamofire/4.0.0, per RFC 7231 §5.5.3.

如果需要自定义头部信息,需要这么来做:

If you need to customize these headers, a custom URLSessionConfiguration should be created, the defaultHTTPHeaders property updated and the configuration applied to a new SessionManager instance.

 Authentication(验证)

支持四种验证机制:

HTTP Basic          HTTP Digest        Kerberos      NTLM

基本的用法:

let user = "user"

let password = "password"

Alamofire.request("https://httpbin.org/basic-auth/\(user)/\(password)")

.authenticate(user: user, password: password)

.responseJSON { response in

debugPrint(response)

}

 四 Downloading Data to a File(下载文件)

Alamofire可以加载数据到内存缓存或者沙盒缓存,Alamofire.request用来将数据保存在内存中,这比较高效,但不适用于大文件的保存;使用Alamofire.download可以将大文件保存到应用的沙盒中。

Alamofire.download("https://httpbin.org/image/png").responseData { response in

if let data = response.result.value {

let image = UIImage(data: data)

}}

如果需要后台下载,需这样设置:

let configuration = URLSessionConfiguration.background(withIdentifier: "com.example.app.background")

let sessionManager = Alamofire.SessionManager(configuration: configuration)

sessionManager.download("https://httpbin.org/image/png").responseData { response in

if let data = response.result.value {

let image = UIImage(data: data)

}}

使用DownloadFileDestination

可以将文件从临时路径移动到目标路径:

let destination: DownloadRequest.DownloadFileDestination = { _, _ in

let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]

let fileURL = documentsURL.appendPathComponent("pig.png")

return (fileURL, [.removePreviousFile, .createIntermediateDirectories])

}

Alamofire.download(urlString, to: destination).response { response in

print(response)

if response.error == nil, let imagePath = response.destinationURL?.path {

let image = UIImage(contentsOfFile: imagePath)

}}

也可以使用建议的路径:

let destination = DownloadRequest.suggestedDownloadDestination(directory: .documentDirectory)

Alamofire.download("https://httpbin.org/image/png", to: destination)

监测下载进度:

Alamofire.download("https://httpbin.org/image/png")

.downloadProgress { progress in

print("Download Progress: \(progress.fractionCompleted)")

}

.responseData { response in

if let data = response.result.value {

let image = UIImage(data: data)

}}

可以将下载的进程加入到一个GCD队列中:

let utilityQueue = DispatchQueue.global(qos: .utility)

Alamofire.download("https://httpbin.org/image/png")

.downloadProgress(queue: utilityQueue) { progress in

print("Download Progress: \(progress.fractionCompleted)")

}

.responseData { response in

if let data = response.result.value {

let image = UIImage(data: data)

}}

 五 其他部分:

 Statistical Metrics(统计)

统计网络延时,响应时间等数据

Alamofire.request("https://httpbin.org/get").responseJSON { response in

print(response.timeline)

}

cURL Command Output (调试工具)

CustomStringConvertible

let request = Alamofire.request("https://httpbin.org/ip")

print(request)

// GET https://httpbin.org/ip (200)

CustomDebugStringConvertible

let request = Alamofire.request("https://httpbin.org/get", parameters: ["foo": "bar"])

debugPrint(request)

参考代码

上一篇下一篇

猜你喜欢

热点阅读