Alamofire是AFNetworking的作者編寫的在Swift中使用的網(wǎng)絡(luò)類庫(kù),使用起來邏輯清晰明了,也很容易上手.
當(dāng)然AFNetworking在Swift中依然是可以使用的,不過我不推薦那么做.
安裝Alamofire
可以通過Cocoapods的方式進(jìn)行安裝,podfile配置如下:<pre>
platform :ios, '8.0'
use_frameworks!
target '你的工程名稱' do
pod 'Alamofire', '~> 3.3.0'
end
</pre>
然后到終端執(zhí)行pod install就可以了,使用之前先import一下<pre>import Alamofire</pre>
基本使用,請(qǐng)求數(shù)據(jù)
普通數(shù)據(jù)請(qǐng)求
<pre>
//我把請(qǐng)求放在了button的點(diǎn)擊事件里面
@IBAction func onBtnClick(sender: UIButton) {
//這里我使用一個(gè)查詢手機(jī)號(hào)碼歸屬地的接口為例,
Alamofire.request(.GET,, requestURL,parameters: ["phone":phoneNumber],encoding: .URL,headers: ["apix-key":apiKey]).responseJSON { (response) in
//是否請(qǐng)求成功
// if response.result.isSuccess{}
if let jsonValue = response.result.value {
print(jsonValue)
}
}
}</pre>
<pre>
Alamofire.request(Method, URLString, parameters, encoding, headers)
//這是一個(gè)完整的Alamofire.Request的初始化方法,其中:
//Method,請(qǐng)求方式,如:.GET .POST .DELETE等
//URLString,請(qǐng)求接口
//parameters,請(qǐng)求參數(shù),字典類型,如果是GET方法請(qǐng)求數(shù)據(jù),傳入的參數(shù)將會(huì)被轉(zhuǎn)換為key1=value1&key2=value2的形式
//encoding,編碼方式,Alamofire提供一個(gè)枚舉來表示請(qǐng)求所用編碼,如.URL,.JSON,那么GET方式請(qǐng)求數(shù)據(jù)一般使用.URL編碼方式
//headers,請(qǐng)求頭,對(duì)應(yīng)于在NSURLRequest中的屬性allHTTPHeaderFields
</pre>
這里是一個(gè)普通的GET請(qǐng)求,傳入的參數(shù)Alamofire自動(dòng)以key=value&kay2=value2的形式拼接,如果請(qǐng)求是POST或者需要把請(qǐng)求參數(shù)已JSON的形=形式傳輸?shù)脑?encoding參數(shù)傳入.JSON即可
responseJSON閉包中我們得到的參數(shù)是一個(gè)結(jié)構(gòu)體,里面分別包含了此次請(qǐng)求的request對(duì)象,返回?cái)?shù)據(jù),請(qǐng)求結(jié)果等.
響應(yīng)結(jié)果控制
Alamofire.request()返回的是一個(gè)Request對(duì)象,Request對(duì)象的參數(shù)都是本次請(qǐng)求中附帶的參數(shù),responseJSON是對(duì)返回結(jié)果的控制,針對(duì)返回結(jié)果為JSON數(shù)據(jù)的情況,Alamofire中還提供了處理其他返回結(jié)果地方法:
<pre>
response()
responseData()//二進(jìn)制數(shù)據(jù)
responseString(encoding: NSStringEncoding)//字符串結(jié)果
responseJSON(options:NSJSONReadingOptions)//JSON數(shù)據(jù)
responsePropertyList(options: NSPropertyListReadOptions)//屬性列表
///響應(yīng)方式應(yīng)該試服務(wù)器返回結(jié)果而定,如果服務(wù)器給你的是JSON數(shù)據(jù)那么就用responseJSON,如果是其他數(shù)據(jù)那么也使用對(duì)應(yīng)的
</pre>
使用validate()驗(yàn)證是否請(qǐng)求成功
<pre>
Alamofire.request(.GET, requestURL,parameters:["phone":phoneNumber],encoding: .URL,headers: ["apix-key":apiKey]).validate().responseJSON { (response) in
//是否請(qǐng)求成功
switch response.result{
case .Success:
print("數(shù)據(jù)請(qǐng)求成功")
case .Failure(let error):
print(error)
}
}</pre>
validate()將確認(rèn)響應(yīng)的狀態(tài)編碼控制在可接受的范圍200-299內(nèi),如果驗(yàn)證失敗,那么在響應(yīng)的處理方法內(nèi)部將會(huì)出現(xiàn)一個(gè)錯(cuò)誤.
上傳數(shù)據(jù)
<pre>
一個(gè)簡(jiǎn)單地上傳文件的小栗子
let fileURL = NSBundle.mainBundle().URLForResource("1", withExtension: "jpg")
Alamofire.upload(.POST, uploadURL, file: fileURL!)
//這里的前面兩個(gè)參數(shù)分別是連接方式,請(qǐng)求接口,第三個(gè)參數(shù)就是需要上傳的文件的本地URL
</pre>
當(dāng)然也可以使用NSData的形式上傳:
<pre>
Alamofire.upload(.POST, uploadURL, data: "upload Data".dataUsingEncoding(NSUTF8StringEncoding)!)
</pre>
其他的還有使用MultipartFormData等,這里就不做介紹了.
上傳附件時(shí)監(jiān)測(cè)進(jìn)度
Alamofire.upload(.POST, uploadURL, data: "upload Data".dataUsingEncoding(NSUTF8StringEncoding)!).progress { (written, totalWritten, totalNeedsToWrite) in
print("written bytes \(written) totalWritten \(totalWritten) totalBytes\(totalNeedsToWrite)")
///每次上傳一部分?jǐn)?shù)據(jù)就會(huì)回調(diào)此閉包.
}
同樣的,不管是上傳還是請(qǐng)求數(shù)據(jù)或是下載文件,我們都可以得到服務(wù)器的響應(yīng),所以上傳也是可以使用response系列方法的:
Alamofire.upload(.POST, uploadURL, data: "upload Data test ".dataUsingEncoding(NSUTF8StringEncoding)!).progress { (written, totalWritten, totalNeedsToWrite) in
print("written bytes \(written) totalWritten \(totalWritten) totalBytes\(totalNeedsToWrite)")
}.responseJSON { (response) in
print(response)//服務(wù)器對(duì)本次數(shù)據(jù)上傳的響應(yīng)
}```
有上傳就有下載,Alamofire提供Alamofire.download()方法來執(zhí)行下載操作:
///本例中所下載的文件是在網(wǎng)上隨便找的一張圖片
Alamofire.download(.GET, "http://pic.to8to.com/attch/day_160218/20160218_d968438a2434b62ba59dH7q5KEzTS6OH.png") { (URL, response) -> NSURL in
var path = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
path += "/(response.suggestedFilename!)"
return NSURL.fileURLWithPath(path)
}
download方法接受一個(gè)閉包,此閉包在文件下載完成后調(diào)用,我們需要在閉包中返回文件下載完畢之后,保存此文件的資源路徑,你也可以單獨(dú)拆分一個(gè)函數(shù),然后傳入函數(shù)名即可
如果覺得這樣比較麻煩或者沒有必要在閉包中那些代碼,我們可以使用默認(rèn)的資源路徑:
///這里使用的是系統(tǒng)的Document路徑
let destina = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)
Alamofire.download(.GET, "http://pic.to8to.com/attch/day_160218/20160218_d968438a2434b62ba59dH7q5KEzTS6OH.png",destination: destina)
同樣的,下載文件也可以檢測(cè)下載進(jìn)度
let destina = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)
Alamofire.download(.GET, "http://pic.to8to.com/attch/day_160218/20160218_d968438a2434b62ba59dH7q5KEzTS6OH.png",destination: destina).progress { (downloadBytes, totalDownloadBytes, totalBytesToDownload) in
//在此實(shí)現(xiàn)檢測(cè)下載進(jìn)度邏輯
}
如果需要實(shí)現(xiàn)斷點(diǎn)續(xù)傳來下載文件的話,實(shí)現(xiàn)起來也是比較簡(jiǎn)單,首先,Alamofire提供了對(duì)應(yīng)的download方法:
Alamofire.download(resumeData: NSData() , destination: destina)
第一個(gè)參數(shù)應(yīng)該傳入已經(jīng)下載得到的數(shù)據(jù),就可以在已經(jīng)下載數(shù)據(jù)的基礎(chǔ)上繼續(xù)下載,那么我們需要做的事就只有在下載出現(xiàn)錯(cuò)誤或者暫停的時(shí)候把已下載數(shù)據(jù)保存起來就可以了,大致的實(shí)現(xiàn)思路就是這樣,我這里就不作演示了.
暫時(shí)先總結(jié)到這里,如果本文中有什么寫的不正確的地方,歡迎指正!