網絡層是我們在日常開發中必須用到的框架。Alamofire是在swift開發中比較常用的一個開源框架,本文就是介紹Alamofire的相關使用。
Alamofire框架的介紹和使用
一. 什么是Alamofire
(1)Alamofire 的前身是 AFNetworking。AFNetworking 是 iOS 和 OS X 上很受歡迎的第三方HTTP網絡基礎庫。
(2)其實 AFNetwork 的前綴 AF 便是 Alamofire 的縮寫。
(3)Swift發布后,AFNetworking的作者又用Swift語言寫了個相同功能的庫,這便是 Alamofire。
(4)Alamofire 本質是基于URLSession
,并做了封裝。使用 Alamofire 可以讓我們網絡請求相關代碼(如獲取數據,提交數據,上傳文件,下載文件等)更加簡潔易用。
二. Alamofire的使用
1.Alamofire使用了步驟
我在使用這個框架的時候是用的cocoapods導入的方式,當然也可以手動導入,本人感覺使用cocoapods比較方便,下面就是介紹一下cocoapods導入該庫的方法:(如果有的同學想要知道手動導入的步驟,可以參考這鏈接Alamofire手動導入方法)
(1).更新cocoapods的版本
cocoapods的使用方法我想對于大多數開發者來說肯定是再熟悉不過了,這里就略過了,如果有什么疑問的地方可以去看一下我之前寫過的文章關于cocoapods的使用,或者查閱一些資料。這里我做了一些特殊的處理方法。如果我們直接使用之前版本安裝的cocoapods來更新Alamofire最新版本可能會更新失敗,這里我們需要把cocoapods的版本升級到1.1.0+的版本才可以。
首先提到的一點是,在xcode8之后的cocoapods的鏡像已經有taobao的gem源換成了ruby.china的gem源。但是我在更換了路徑之后還是失敗了很多次,最后就索性換成了 使用國內的spec鏡像就可以了!
cd ~/.cocoapods/repos
git clone https://git.coding.net/CocoaPods/Specs.git master
如果顯示master文件存在可以在~/.cocoapods/repos 路徑下先把master文件刪除,在進行替換,不過這個過程比較緩慢,請耐心等待即可。
更換完路徑后,再使用:
sudo gem install cocoapods --pre
更新cocoapods的版本即可(可以參照這里的一篇文章點擊這里)
(2).更新完cocoapods版本之后就是用cocoapods更新Alamofire的最新版本即可。
2.Alamofire的功能特點
(1).鏈式的請求/響應方法
(1).URL / JSON / plist參數編碼
(2).上傳類型支持:文件(File )、數據(Data )、流(Stream)以及MultipartFormData
(3).支持文件下載,下載支持斷點續傳
(4).支持使用NSURLCredential進行身份驗證
(5).HTTP響應驗證
(6).TLS Certificate and Public Key Pinning
(7).Progress Closure & NSProgress
3.Alamofire的網絡請求
(1).get請求
// get
func GET_Request() {
let parameters : [String : Any] = ["foo": "bar"]
//1,responseJSON
Alamofire.request(main_url, method: .get, parameters: parameters).responseJSON { (returnResult) in
print("GET_Request --> GET 請求 --> returnResult = \(returnResult)")
if let json = returnResult.result.value {
print("firstMethod --> responseJSON --> \(json)")
/* 返回請求地址、數據、和狀態結果等信息
print("firstMethod --> responseJSON() --> \(returnResult.request!)")
print("firstMethod --> responseJSON() --> \(returnResult.data!)")
print("firstMethod --> responseJSON() --> \(returnResult.result)")
*/
}
}
(2).post請求
// post
func POST_Request(){
//request(host_url, method:.post, parameters : parameters)
let urlstring = "\(host_url)type=\(top)&key=\(appkey)"
Alamofire.request(urlstring, method:.post).responseJSON { (returnResult) in
print("POST_Request --> post 請求 --> returnResult = \(returnResult)")
// switch returnResult.result.isSuccess {
// case true:
// print("數據獲取成功!")
// case false:
// print(returnResult.result.error ?? Error.self)
// }
}
}
(3).響應處理(Response Handling)
除了上面樣例使用的responseJSON(處理json類型的返回結果)外,Alamofire還提供了許多其他類型的響應處理方法:
response()
responseData()
responseString(encoding: NSStringEncoding)
responseJSON(options:NSJSONReadingOptions)
responsePropertyList(options: NSPropertyListReadOptions)
//2,response()
// Alamofire.request(main_url, method:.get, parameters: parameters).response { (response) in
// print("response = \(response.response)")
// print("data = \(response.data)")
// print("error = \(response.error)")
//
//
// if let data = response.data , let utf8string = String(data: data , encoding:.utf8) {
// print("utf8string = \(utf8string)")
// }
//
// }
//3,responseData()
// Alamofire.request(main_url, method: .get, parameters: parameters).responseData { (responseData) in
// debugPrint("responseData : \(responseData)")
//
// if let data = responseData.data, let utf8string = String(data: data, encoding: .utf8) {
// print("utf8string = \(utf8string)")
// }
//
// }
// //4,responseString
// Alamofire.request(main_url, method: .get, parameters: parameters).responseString { (responseString) in
// debugPrint("responseString() --> Sucess = \(responseString.result.isSuccess)")
// debugPrint("responseString : \(responseString)")
//
// if let data = responseString.data , let utf8string = String(data: data, encoding: .utf8) {
// print("utf8string = \(utf8string)")
// }
// }
// 5. responsePropertyList() 下面解釋
//6.在response方法中還有一個方法 參數:queue:請求隊列 --> 就是默認在主線程中執行~但是我們可以自定義調度隊列。
// let customQueue = DispatchQueue.global(qos: .utility)
// Alamofire.request(main_url, method: .get, parameters: parameters).responseJSON(queue: customQueue) { (returnResult) in
// print("請求隊列 --> \(returnResult)")
// }
(4)下載,上傳
//下載 上傳
func downloadAnduploadMethod() {
//下載文件
Alamofire.download(host_img_url).responseJSON { (returnResult) in
if let data = returnResult.result.value {
let image = UIImage(data : data as! Data)
print("\(image)")
}else {
print("download is fail")
}
}
//還可以看下載進度
Alamofire.download(host_img_url).downloadProgress { (progress) in
print("download progress = \(progress.fractionCompleted)")
}.responseJSON { (returnResult) in
if let data = returnResult.result.value {
let image = UIImage(data : data as! Data)
print("\(image)")
}else {
print("download is fail")
}
}
}
具體的代碼,參照這里demo
這里只是簡單的介紹一下方法,后續會繼續介紹一些功能使用,希望共同進步,大家一起加油!!!