Swift Alamofire

最近AFNetworking的作者M(jìn)att Thompson 提出了一個(gè)新的類似AFNetworking的網(wǎng)絡(luò)基礎(chǔ)庫(kù),并且專門使用最新的Swift語(yǔ)言寫的,名為 Alamofire.

一、正常導(dǎo)入,CocoaPods

1-1、注意下CocoaPods版本

gem install cocoapods

CocoaPods 0.39.0+ is required to build Alamofire 3.0.0+.

1-2、vim Podfile

  platform :ios, '8.0'
  use_frameworks!
  pod 'Alamofire' 
  //然后 pod install 就OK了 

1-3、導(dǎo)入Alamfire 就可以正常使用了

  import Alamofire 

注意目前可能會(huì)出現(xiàn)這個(gè)警告;Cannot load underlying module for 'Alamofire',可以先忽略它,直接 build就沒(méi)了

二、基本使用

GET請(qǐng)求

普通的get請(qǐng)求

 下面是一個(gè)天氣預(yù)報(bào)的請(qǐng)求,時(shí)間久了,key 會(huì)失效
  let parameters:Dictionary = ["key":"93c921ea8b0348af8e8e7a6a273c41bd"]
    Alamofire.request(.GET, "http://apis.haoservice.com/weather/city", parameters: parameters)
        .responseJSON { response in

            print("result==\(response.result)")   // 返回結(jié)果,是否成功
            if let jsonValue = response.result.value {
                /*
                error_code = 0
                reason = ""
                result = 數(shù)組套字典的城市列表
                */
                print("code: \(jsonValue["error_code"])")
            }
    }
     /*
    result==SUCCESS
    code: Optional(0)
    */

帶head的get請(qǐng)求

 let headers = ["apikey":"a566eb03378211f7dc9ff15ca78c2d93"]
 Alamofire.request(.GET, "http://apis.baidu.com/heweather/pro/weather?city=beijing", headers: headers)
        .responseJSON { response in
            print("result==\(response.result)")
            if let jsonValue = response.result.value {
                
                print("weNeedReuslt ==  \(jsonValue)")
            }
  
   }
POST 請(qǐng)求

先看看Alamofire 定義了許多其他的HTTP 方法(HTTP Medthods)可以使用。

public enum Method: String {
case OPTIONS, GET, HEAD, POST, PUT, PATCH, DELETE, TRACE, CONNECT
}

使用GET類型請(qǐng)求的時(shí)候,參數(shù)會(huì)自動(dòng)拼接在url后面,使用POST類型請(qǐng)求的時(shí)候,參數(shù)是放在在HTTP body里傳遞,url上看不到的

let parameters:Dictionary = ["key":"93c921ea8b0348af8e8e7a6a273c41bd"]
Alamofire.request(.POST, "http://apis.haoservice.com/weather/city", parameters: parameters)
        .responseJSON { response in
            
            print("result==\(response.result)")   // 返回結(jié)果,是否成功
            if let jsonValue = response.result.value {
                /*
                error_code = 0
                reason = ""
                result = 數(shù)組套字典的城市列表
                */
                print("code: \(jsonValue)")
            }
 }

至于加header的post 請(qǐng)求,實(shí)際上也是GET 一樣的

注意點(diǎn)1: 參數(shù)編碼方式

除了默認(rèn)的方式外,Alamofire還支持URL、URLEncodedInURL、JSON、Property List以及自定義格式方式編碼參數(shù)。

public enum ParameterEncoding {
      case URL
      case URLEncodedInURL
      case JSON
      case PropertyList(NSPropertyListFormat, NSPropertyListWriteOptions)
      case Custom((URLRequestConvertible, [String: AnyObject]?) -> (NSMutableURLRequest, NSError?))
}

//想要把一個(gè)字典類型的數(shù)據(jù),使用json格式發(fā)起POST請(qǐng)求

 let parameters = [
        "one": [1,2,3],
        "two": ["apple": "pig"]
    ]
    
 Alamofire.request(.POST, "http://www.example.com/service", parameters: parameters, encoding: .JSON)
注意點(diǎn)2:validate()

將其與請(qǐng)求和響應(yīng)鏈接,以確認(rèn)響應(yīng)的狀態(tài)碼在默認(rèn)可接受的范圍(200到299)內(nèi)。如果認(rèn)證失敗,響應(yīng)處理方法將出現(xiàn)一個(gè)相關(guān)錯(cuò)誤,我們可以根據(jù)不同在完成處理方法中處理這個(gè)錯(cuò)誤。比如下面的樣例,成功時(shí)會(huì)打印成功信息,失敗時(shí)輸出具體錯(cuò)誤信息。

  Alamofire.request(.GET, "http://apis.haoservice.com/weather/city", parameters: ["apikey":"a566eb03378211f7dc9ff15ca78c2d93"])
        .validate()
        .responseJSON { response in
            switch response.result {
            case .Success:
                print("數(shù)據(jù)獲取成功!")
            case .Failure(let error):
                print(error)
            }
    }
注意點(diǎn)3:響應(yīng)處理方法

觀察上面幾個(gè)請(qǐng)求,我都是使用樣例的responseJSON(處理json類型的返回結(jié)果)外,Alamofire還提供了許多其他類型的響應(yīng)處理方法:

response()
responseData()
responseString(encoding: NSStringEncoding)
responseJSON(options: NSJSONReadingOptions)
responsePropertyList(options: NSPropertyListReadOptions)

我們可以根據(jù)我的實(shí)際情況,選擇自己需要的。

例如 responseData()
 Alamofire.request(.GET, "http://apis.haoservice.com/weather/city", parameters: ["apikey":"a566eb03378211f7dc9ff15ca78c2d93"])
        .responseData { response in
            print(response.request)
            print(response.response)
            print(response.result)
    }

暫時(shí)基本使用,總結(jié)到此,持續(xù)更新中····??

備注參考

https://github.com/Alamofire/Alamofire
http://www.hangge.com/blog/cache/detail_970.html
http://www.cnblogs.com/iCocos/p/4550570.html

最后編輯于
?著作權(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)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

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