Alamofire的使用

要求的使用環(huán)境:
iOS 10.0+ / macOS 10.12+ / tvOS 10.0+ / watchOS 3.0+
Xcode 10.2+
Swift 5+

Alamofire 源碼GitHub下載地址:https://github.com/Alamofire/Alamofire

安裝方法:CocoaPods

platform :ios, '10.0'
use_frameworks!

target '項(xiàng)目名稱' do
    pod 'Alamofire', '~> 5.0.0-beta.5'
end

使用:
發(fā)請(qǐng)求

Alamofire.request("http://baidu.com/")

Alamofire默認(rèn)情況下包含五種不同的響應(yīng)handler:

// 響應(yīng) Handler - 未序列化的響應(yīng)
func response(
    queue: DispatchQueue?,
    completionHandler: @escaping (DefaultDataResponse) -> Void)
    -> Self

// 響應(yīng)數(shù)據(jù) Handler - 序列化成數(shù)據(jù)類型
func responseData(
queue: DispatchQueue?,
 completionHandler: @escaping (DataResponse<Data>) -> Void)
    -> Self

// 響應(yīng)字符串 Handler - 序列化成字符串類型
func responseString(
    queue: DispatchQueue?,
    encoding: String.Encoding?,
    completionHandler: @escaping (DataResponse<String>) -> Void)
    -> Self

// 響應(yīng) JSON Handler - 序列化成Any類型
func responseJSON(
    queue: DispatchQueue?,
    completionHandler: @escaping (DataResponse<Any>) -> Void)
    -> Self

// 響應(yīng) PropertyList (plist) Handler - 序列化成Any類型
func responsePropertyList(
    queue: DispatchQueue?,
    completionHandler: @escaping (DataResponse<Any>) -> Void))
    -> Self

所有的響應(yīng)handler都不會(huì)對(duì)響應(yīng)進(jìn)行驗(yàn)證。也就是說響應(yīng)狀態(tài)碼在400..<500和500..<600范圍內(nèi),都不會(huì)觸發(fā)錯(cuò)誤。

響應(yīng)數(shù)據(jù) Handler
responseData handler使用responseDataSerializer(這個(gè)對(duì)象把服務(wù)器的數(shù)據(jù)序列化成其他類型)來提取服務(wù)器返回的數(shù)據(jù)。如果沒有返回錯(cuò)誤并且有數(shù)據(jù)返回,那么響應(yīng)Result將會(huì)是.success,value是Data類型。

Alamofire.request("https://httpbin.org/get").responseData { response in
    debugPrint("All Response Info: \(response)")

    if let data = response.result.value, let utf8Text = String(data: data, encoding: .utf8) {
        print("Data: \(utf8Text)")
    }
}

響應(yīng)字符串 Handler
responseString handler使用responseStringSerializer對(duì)象根據(jù)指定的編碼格式把服務(wù)器返回的數(shù)據(jù)轉(zhuǎn)換成String。如果沒有返回錯(cuò)誤并且服務(wù)器的數(shù)據(jù)成功地轉(zhuǎn)換為String,那么響應(yīng)Result將會(huì)是.success,value是String類型。

Alamofire.request("https://httpbin.org/get").responseString { response in
    print("Success: \(response.result.isSuccess)")
    print("Response String: \(response.result.value)")
}

如果沒有指定編碼格式,將會(huì)使用服務(wù)器的HTTPURLResponse指定的格式。如果服務(wù)器無法確定編碼格式,那么默認(rèn)使用.isoLatin1。

響應(yīng) JSON Handler
responseJSON handler使用responseJSONSerializer根據(jù)指定的JSONSerialization.ReadingOptions把服務(wù)器返回的數(shù)據(jù)轉(zhuǎn)換成Any類型。如果沒有返回錯(cuò)誤并且服務(wù)器的數(shù)據(jù)成功地轉(zhuǎn)換為JSON對(duì)象,那么響應(yīng)Result將會(huì)是.success,value是Any類型。

Alamofire.request("https://httpbin.org/get").responseJSON { response in
    debugPrint(response)

    if let json = response.result.value {
        print("JSON: \(json)")
    }
}

所有JSON的序列化,都是使用JSONSerialization完成的。

HTTP方法
HTTPMethod列舉了下面的這些方法:

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"
}

網(wǎng)絡(luò)請(qǐng)求:

 let para = ["name":"zhagnshan"]
 let header = ["Accept": "*/*", "X-Requested-With": "APP"]
 //        encoding:
 //        URLEncoding //和URL相關(guān)的編碼
 //        JSONEncoding //把參數(shù)字典編碼成JSONData后賦值給request的httpBody
  //        PropertyListEncoding //把參數(shù)字典編碼成PlistData后賦值給request的httpBody
 request("https://www.baidu.com", method: HTTPMethod.get, parameters: para, encoding: JSONEncoding, headers: header).responseJSON { (response) in
     print(response)
     if response.result.isSuccess{
         //請(qǐng)求成功
     }else{
         //請(qǐng)求失敗
     }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容