一 安裝:
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
完成之后添加一下動(dòng)態(tài)庫(kù)儒旬,如下圖:
?二 基礎(chǔ)用法:
Response handler
Alamofire 的網(wǎng)絡(luò)操作都是異步進(jìn)行(用response handler)的,最基本的請(qǐng)求代碼如下:
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 默認(rèn)包含物種類型的response handlers:response responseString responseJSON responseData
兩種高級(jí)的方式:
1.Chained Response Handlers(鏈?zhǔn)骄纠⒁猓簳?huì)訪問服務(wù)器數(shù)據(jù)多次)
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 默認(rèn)是在主線程上運(yùn)行的疏唾,可以添加到GCD隊(duì)列中。
let utilityQueue = DispatchQueue.global(qos: .utility)
Alamofire.request("https://httpbin.org/get").responseJSON(queue: utilityQueue) { response in
print("Executing response handler on utility queue")
}
判斷服務(wù)器返回的數(shù)據(jù)有效性的方式:
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相關(guān):
?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"
}
默認(rèn)方法是 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(參數(shù)編碼)
Alamofire 支持3種類型的參數(shù)編碼:URL, JSON and PropertyList摊滔。也可以自定義類型阴绢,需支持ParameterEncoding協(xié)議。
?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提供了默認(rèn)的頭部艰躺,內(nèi)容如下:
? 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(驗(yàn)證)
支持四種驗(yàn)證機(jī)制:
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可以加載數(shù)據(jù)到內(nèi)存緩存或者沙盒緩存,Alamofire.request用來將數(shù)據(jù)保存在內(nèi)存中腺兴,這比較高效棒妨,但不適用于大文件的保存;使用Alamofire.download可以將大文件保存到應(yīng)用的沙盒中。
Alamofire.download("https://httpbin.org/image/png").responseData { response in
if let data = response.result.value {
let image = UIImage(data: data)
}}
如果需要后臺(tái)下載券腔,需這樣設(shè)置:
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
可以將文件從臨時(shí)路徑移動(dòng)到目標(biāo)路徑:
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)
監(jiān)測(cè)下載進(jìn)度:
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)
}}
可以將下載的進(jìn)程加入到一個(gè)GCD隊(duì)列中:
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(統(tǒng)計(jì))
統(tǒng)計(jì)網(wǎng)絡(luò)延時(shí),響應(yīng)時(shí)間等數(shù)據(jù)
Alamofire.request("https://httpbin.org/get").responseJSON { response in
print(response.timeline)
}
cURL Command Output (調(diào)試工具)
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)