[快速學會Swift第三方庫] Alamofire篇
[快速學會Swift第三方庫] Alamofire篇
Alamofire是 Swift 語言的 HTTP 網路開發工具包,AFNetworking的 Swift 版,使用起來相當簡單。
目錄
編碼之前
匯入Alamofire
推薦使用CocoaPods進行匯入,CocoaPods是一個負責管理iOS專案中第三方開源庫的工具,安裝CocoaPods之後使用命令列就能輕鬆地對所有第三方開源庫進行安裝和更新,而不需要每次上GitHub去下載。
CocoaPods的安裝過程傳送門:iOS 9 匯入類庫全面詳盡過程(Ruby安裝->CocoaPods安裝->匯入類庫)
手動下載:GitHub-Alamofire 主頁
裝好CocoaPods後,修改Podfile檔案內容為如下:
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '9.0'
use_frameworks!
target 'Web' do
pod 'Alamofire', '~> 3.4'
end
xcodeproj 'Desktop/Web/Web.xcodeproj'
target後面為工程名,最後一行為工程路徑(這裡的Web是我的工程名)
再執行命令:
$ pod install
其他操作
另外還需要在Target->工程名->Build Settings->Search Paths->User Header Search Paths處新增Alamofire所在的目錄:
最後在你需要用到Alamofire的類中加上:
import Alamofire
Web請求
示例程式碼
func webRequst() {
Alamofire.request(.GET, "http://blog.csdn.net/sps900608", parameters: nil)
.responseData { (response) in
print("webRequest:\(response.result)")
//注意:webView需自定義!
self.webView.loadData(response.result.value!, MIMEType: "text/html", textEncodingName: "utf-8", baseURL: NSURL())
}
}
執行結果:
webRequest:SUCCESS
資料請求(JSON)
示例程式碼
func jsonRequest() {
let parameters = [ "foo": "bar","baz": ["a", 1],"qux": ["x": 1,"y": 2,"z": 3]]
// HTTP body: foo=bar&baz[]=a&baz[]=1&qux[x]=1&qux[y]=2&qux[z]=3
Alamofire.request(.POST, "https://httpbin.org/post", parameters: parameters)
.responseJSON { (response) in
print("jsonRequest:\(response.result)")
if let JSON = response.result.value {
print("JSON: \(JSON)")
}
}
}
執行結果
jsonRequest:SUCCESS
JSON: {
args = {
};
data = "";
files = {
};
form = {
"baz[]" = (
a,
1
);
foo = bar;
"qux[x]" = 1;
"qux[y]" = 2;
"qux[z]" = 3;
};
headers = {
Accept = "*/*";
"Accept-Encoding" = "gzip;q=1.0, compress;q=0.5";
"Accept-Language" = "en-US;q=1.0";
"Content-Length" = 70;
"Content-Type" = "application/x-www-form-urlencoded; charset=utf-8";
Host = "httpbin.org";
"User-Agent" = "Web/com.applelab.Web (1; OS Version 9.3 (Build 13E230))";
};
json = "<null>";
origin = "202.115.52.205";
url = "https://httpbin.org/post";
}
上傳檔案
示例程式碼
func upload() {
// 可任意拖一張圖片到工程目錄下重新命名為“123.png”
let fileURL = NSBundle.mainBundle().URLForResource("123", withExtension: "png")!
Alamofire.upload(.POST, "https://httpbin.org/post", file: fileURL)
.progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in
//如果要修改介面UI,需要放到主執行緒中進行
dispatch_async(dispatch_get_main_queue()) {
print("Total bytes written on main queue: \(totalBytesWritten)")
}
}
.responseString { (response) in
debugPrint("uploadRequest:\(response)")
}
}
執行結果
Total bytes written on main queue: 3538
"uploadRequest:SUCCESS: {\n \"args\": {}, \n \"data\": \"data:application/octet-stream;base64,(此處省略檔案data資訊)==\", \n \"files\": {}, \n \"form\": {}, \n \"headers\": {\n \"Accept\": \"*/*\", \n \"Accept-Encoding\": \"gzip;q=1.0, compress;q=0.5\", \n \"Accept-Language\": \"en-US;q=1.0\", \n \"Content-Length\": \"3538\", \n \"Content-Type\": \"application/octet-stream\", \n \"Host\": \"httpbin.org\", \n \"User-Agent\": \"Web/com.applelab.Web (1; OS Version 9.3 (Build 13E230))\"\n }, \n \"json\": null, \n \"origin\": \"202.115.52.205\", \n \"url\": \"https://httpbin.org/post\"\n}\n"
下載檔案
示例程式碼
func download() {
//設定下載目標路徑為推薦下載目標路徑
let destination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)
//列印下載目標路徑
print(NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0])
Alamofire.download(.GET, "https://httpbin.org/stream/100", destination: destination)
.response { (_, _, _, error) in
if let error = error {
print("Failed with error: \(error)")
} else {
print("Downloaded file successfully")
}
}
}
執行結果
/Users/nothinglhw/Library/Developer/CoreSimulator/Devices/560AA615-771E-499E-A8A9-AA6BE3781903/data/Containers/Data/Application/C715D9C3-57C9-40AF-88EC-EE4B86EB06D2/Documents
Downloaded file successfully
如果是在模擬器中執行,開啟該目錄可以看到多了一個名字為“100”的檔案:
開啟該檔案可以看到:
{"url": "https://httpbin.org/stream/100", "headers": {"Host": "httpbin.org", "Accept-Language": "en-US;q=1.0", "Accept-Encoding": "gzip;q=1.0, compress;q=0.5", "Accept": "*/*", "User-Agent": "Web/com.applelab.Web (1; OS Version 9.3 (Build 13E230))"}, "args": {}, "id": 0, "origin": "202.115.52.205"}
{"url": "https://httpbin.org/stream/100", "headers": {"Host": "httpbin.org", "Accept-Language": "en-US;q=1.0", "Accept-Encoding": "gzip;q=1.0, compress;q=0.5", "Accept": "*/*", "User-Agent": "Web/com.applelab.Web (1; OS Version 9.3 (Build 13E230))"}, "args": {}, "id": 1, "origin": "202.115.52.205"}
{"url": "https://httpbin.org/stream/100", "headers": {"Host": "httpbin.org", "Accept-Language": "en-US;q=1.0", "Accept-Encoding": "gzip;q=1.0, compress;q=0.5", "Accept": "*/*", "User-Agent": "Web/com.applelab.Web (1; OS Version 9.3 (Build 13E230))"}, "args": {}, "id": 2, "origin": "202.115.52.205"}
{"url": "https://httpbin.org/stream/100", "headers": {"Host": "httpbin.org", "Accept-Language": "en-US;q=1.0", "Accept-Encoding": "gzip;q=1.0, compress;q=0.5", "Accept": "*/*", "User-Agent": "Web/com.applelab.Web (1; OS Version 9.3 (Build 13E230))"}, "args": {}, "id": 3, "origin": "202.115.52.205"}
{"url": "https://httpbin.org/stream/100", "headers": {"Host": "httpbin.org", "Accept-Language": "en-US;q=1.0", "Accept-Encoding": "gzip;q=1.0, compress;q=0.5", "Accept": "*/*", "User-Agent": "Web/com.applelab.Web (1; OS Version 9.3 (Build 13E230))"}, "args": {}, "id": 4, "origin": "202.115.52.205"}
{"url": "https://httpbin.org/stream/100", "headers": {"Host": "httpbin.org", "Accept-Language": "en-US;q=1.0", "Accept-Encoding": "gzip;q=1.0, compress;q=0.5", "Accept": "*/*", "User-Agent": "Web/com.applelab.Web (1; OS Version 9.3 (Build 13E230))"}, "args": {}, "id": 5, "origin": "202.115.52.205"}
{"url": "https://httpbin.org/stream/100", "headers": {"Host": "httpbin.org", "Accept-Language": "en-US;q=1.0", "Accept-Encoding": "gzip;q=1.0, compress;q=0.5", "Accept": "*/*", "User-Agent": "Web/com.applelab.Web (1; OS Version 9.3 (Build 13E230))"}, "args": {}, "id": 6, "origin": "202.115.52.205"}
深入學習
這裡只列出了最常用的幾種操作,如果你希望能夠更加深入地學習Alamofire,可以前往GitHub-Alamofire主頁 !
相關文章
- Alamofire原始碼分析(一)---Alamofire.swift原始碼Swift
- swift 網路請求Alamofire的使用Swift
- Swift網路訪問庫Alamofire訪問httpslocalhost伺服器SwiftHTTPlocalhost伺服器
- Swift 中的網路請求問題 OC(AFNetworking) && Swift(Alamofire)Swift
- 專案常用第三方庫 Swift版Swift
- 關於 Swift 中的 URLSession 和 Alamofire 原始碼閱讀SwiftSession原始碼
- Swift: 用Alamofire做http請求,用ObjectMapper解析JSONSwiftHTTPObjectAPPJSON
- Swift - Alamofire與Cache封裝實現網路快取、下載Swift封裝快取
- Alamofire3.4.1的學習過程
- Swift3 0中如何呼叫OC第三方庫Swift
- dyld: Library not loaded: @rpath/Alamofire.framework/AlamofireFramework
- iOS 開發(四) 常用第三方庫篇iOS
- 快速學會 shell 程式設計程式設計
- Alamofire 原始碼剖析原始碼
- Swift實現快速排序Swift排序
- Golang 第三方庫學習 · xlsxGolang
- Swift學習筆記第四篇(函式)Swift筆記函式
- 快速學會開發微信小程式微信小程式
- 帶你快速學會工廠模式模式
- 快速學會慢查詢SQL排查SQL
- 用最新的 Alamofire(swift 4.1) (帶引數)post方法上傳圖片到伺服器Swift伺服器
- Alamofire-Cookie相關Cookie
- Swift iOS:AutoLayout 快速介紹SwiftiOS
- Swift快速入門筆記Swift筆記
- Swift語言快速入門Swift
- 重學Swift第一篇:類結構探索Swift
- 在成都的怎麼快速學會JavaJava
- 怎樣快速學會一門技術
- Swift相關第三方資源整合Swift
- 15個快速學習蘋果Swift程式語言的入門教程蘋果Swift
- 一篇文章學會 DockerDocker
- 一篇文章學會GitGit
- 【分享篇】Python爬蟲方向的第三方庫合集!Python爬蟲
- Swift教程Swift語言快速入門(內部資料)Swift
- Swift學習筆記第六篇(類,屬性,方法)Swift筆記
- 純Swift專案-序篇Swift
- Swift學習筆記第五篇(閉包和列舉)Swift筆記
- Swift學習筆記第三篇(字串,陣列,集合,字典)Swift筆記字串陣列