全部類型請求,Alamofire
都直接提供,經過Alamofire
直接調用,配置相關參數便可。示例以下:json
let urlStr = "http://onapp.yahibo.top/public/?s=api/test/list"
Alamofire.request(url).responseJSON { (response) in
switch response.result {
case .success(let json):
print(json)
break
case .failure(let error):
print("error:\(error)")
break
}
}
複製代碼
url
支持多種類型,String、URL、Request
,在框架內部已經爲咱們處理好了,怎麼方便怎麼用responseJSON
獲取json
數據request的參數以下:swift
public func request( _ url: URLConvertible, method: HTTPMethod = .get, parameters: Parameters? = nil, encoding: ParameterEncoding = URLEncoding.default, headers: HTTPHeaders? = nil)
複製代碼
get
方法,所以使用中get
方法,不須要配置直接經過url
發起請求Parameters
爲字典類型,默認爲空,會根據method
作不一樣處理let urlStr = "http://onapp.yahibo.top/public/?s=api/test/list"
Alamofire.request(url, method: .post, parameters: ["name":"hibo","password":"123456"]).responseJSON { (response) in
switch response.result {
case .success(let json):
print(json)
break
case .failure(let error):
print("error:\(error)")
break
}
}
複製代碼
method
參數爲post
let videoUrl = "http://onapp.yahibo.top/public/videos/video.mp4"
Alamofire.download(videoUrl, to: { (videoUrl, response) -> (destinationURL: URL, options: DownloadRequest.DownloadOptions) in
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let time = Date().timeIntervalSince1970
let fileURL = documentsURL.appendingPathComponent("\(time).mp4")
print("沙盒路徑:\(documentsURL)")
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}).downloadProgress { (progress) in
print(progress)
}
複製代碼
let imgArr:Array = [UIImage.init(named: "headimg"),UIImage.init(named: "headimg")]
Alamofire.upload(multipartFormData: { (formData) in
formData.append("hibo".data(using: .utf8)!, withName: "name")
formData.append("123456".data(using: .utf8)!, withName: "password")
for i in 0 ... imgArr.count-1 {
let data = imgArr[i]!.pngData()
let fileName = "image_\(i).png"
formData.append(data!, withName: "image[]", fileName: fileName, mimeType: "image/png")
}
}, to: url) { (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (progress) in
print(progress)
}).responseJSON(completionHandler: { (response) in
switch response.result {
case .success(let json):
print(json)
break
case .failure(let error):
print("error:\(error)")
break
}
})
break
case .failure(let error):
print(error)
break
}
print("result:\(result)")
}
複製代碼
image[]
後臺經過image獲取到的是一個數組fileName
圖片名稱result
中監聽上傳進度,獲取上傳結果設置全局對象:api
struct BackgroundManager {
static let shared = BackgroundManager()
let manager: SessionManager = {
let configuration = URLSessionConfiguration.background(withIdentifier:"com.yahibo.background_id")
configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders
return SessionManager(configuration: configuration)
}()
}
複製代碼
調用發起下載請求:數組
BackgroundManager.shared.manager.download(url) { (url, response) -> (destinationURL: URL, options: DownloadRequest.DownloadOptions) in
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileURL = documentsURL.appendingPathComponent("\(self.currentDateStr()).mp4")
return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}.downloadProgress(queue: DispatchQueue.global(qos: .utility)) { (progress) in
print(progress)
}.response(queue: DispatchQueue.global(qos: .utility), completionHandler: { (response) in
print("完成下載:\(response)")
})
複製代碼
開啓後臺下載權限並賦值系統閉包:閉包
//設置此處開啓後臺下載權限
func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {
BackgroundManager.shared.manager.backgroundCompletionHandler = completionHandler
}
複製代碼
後臺下載與其餘請求不一樣,須要開啓權限,並將系統閉包傳遞到請求代理方法中,後臺下載完成,經過閉包通知系統及時刷新界面。
manager
設置爲全局變量爲方便調用。app
實現RequestAdapter協議方法框架
class MyAdapter: RequestAdapter{
func adapt(_ urlRequest: URLRequest) throws -> URLRequest {
var request = urlRequest
request.setValue("hibotoken", forHTTPHeaderField: "token")
request.setValue("device", forHTTPHeaderField: "iOS")
request.setValue("vision", forHTTPHeaderField: "1.0.0")
return request
}
}
複製代碼
MyAdapter
類繼承協議,並實現協議方法設置屬性dom
let url = "http://onapp.yahibo.top/public/?s=api/test/list」
Alamofire.SessionManager.default.adapter = MyAdapter()
Alamofire.request(url).responseJSON { (response) in
switch response.result {
case .success(let json):
print(json)
break
case .failure(let error):
print("error:\(error)")
break
}
}
複製代碼
這裏的default
是個單列,屬性設置一次就好,不用在每次請求前設置。ide
實現RequestAdapter協議方法post
class redireatAdapter: RequestAdapter{
func adapt(_ urlRequest: URLRequest) throws -> URLRequest {
let newURLRequest = URLRequest.init(url: URL.init(string: "http://onapp.yahibo.top/public/?s=api/test")!)
return newURLRequest
}
}
複製代碼
URLRequest
對象,改變了請求url
設置屬性
let url = "http://onapp.yahibo.top/public/?s=api/test/list」
Alamofire.SessionManager.default.adapter = redireatAdapter()
Alamofire.request(url).responseJSON { (response) in
switch response.result {
case .success(let json):
print(json)
break
case .failure(let error):
print("error:\(error)")
break
}
}
複製代碼
該重定向不經常使用,如應用被逆向,給個重定向,就是不給你數據。
同上面協議,建立子類實現方法,調用便可。
實現協議方法
class MyRetrier: RequestRetrier{
var count: Int = 0
func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) {
if count<3 {
completion(true,2)
count += 1
}else{
completion(false,2)
}
}
}
複製代碼
設置屬性
Alamofire.SessionManager.default.retrier = MyRetrier()
複製代碼
請求失敗後,就會隔時從新發送請求。
let urlStr = "http://onapp.yahibo.top/public/?s=api/test/list2"
let url = URL.init(string: urlStr)!
Alamofire.SessionManager.default.retrier = MyRetrier()
Alamofire.request(url).responseJSON {
(response) in
switch response.result{
case .success(let json):
print("json:\(json)")
break
case .failure(let error):
print("error:\(error)")
break
}
}.validate{ (request, response, data) -> Request.ValidationResult in
print(response)
guard let _ = data else {
return .failure(NSError(domain: "沒有數據啊", code: 10086, userInfo: nil))
}
if response.statusCode == 404 {
return .failure(NSError(domain: "密碼錯誤", code: response.statusCode, userInfo: nil))
}
return .success
}
複製代碼
調用
validate
方法,實現參數閉包,在閉包內攔截錯誤消息。 我使用該框架,可能會對框架進一步封裝,對錯誤響應統一處理,如錯誤消息,經過彈框通知用戶,處理loading
視圖。不知道大佬們都怎麼處理。