Alamofire-使用

全部類型請求,Alamofire都直接提供,經過Alamofire直接調用,配置相關參數便可。示例以下:json

一、GET請求

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作不一樣處理

二、POST請求

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)
        }
    }
}
複製代碼
  • 設定從新發送請求3次
  • 延時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視圖。不知道大佬們都怎麼處理。

相關文章
相關標籤/搜索