一 安裝:
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)