Swift使用Alamofire實現網路請求
阿新 • • 發佈:2018-11-08
Alamofire是一個用Swift編寫的HTTP網路庫,由此前熱門開源專案AFNetworking的的作者mattt開發,可非常簡單地用於非同步網路通訊。
要獲取最新版本的 Alamofire,前往https://github.com/Alamofire/Alamofire然後單擊網頁右邊的Download ZIP按鈕。接著在 Finder 中開啟起始專案資料夾,,然後將Alamofire-master資料夾拖入到您的主專案資料夾中。
開啟Alamofire-master資料夾(現在它位於您的專案資料夾中),然後將Alamofire.xcodeprij檔案(注意是藍色圖示!不是白色圖示!)直接拖進 Xcode 中的 AlamofireDemo 專案下面,如下圖所示:
接下來,單擊AlamofireDemo專案,進入General視窗。滾動到Embedded Binaries項,然後單擊其下方的 + 號。選擇Alamofire.framework,最後點選Add完成新增。
生成並執行您的專案以確保沒有任何錯誤出現,然後就可以進入到下一節內容了。
要使用 Alamofire 的話,首先需要匯入它。您需要在每個使用了 Alamofire 類以及函式的檔案中新增這條`import`語句。
import Alamofire
Alamofire 是一個功能強大的,Swift 語言 HTTP 網路開發工具包。支援各種 HTTP Method、JSON、檔案上傳、檔案下載和多種認證方法。
接下來我們來看具體操作
GET請求
Alamofire.request(.GET, "http://httpbin.org/get")
包含引數
Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
包含 Response 處理
Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"]) .response { (request, response, data, error) in println(request) println(response) println(error) }
POST請求
let parameters = [ "foo": "bar", "baz": ["a", 1], "qux": [ "x": 1, "y": 2, "z": 3 ] ] Alamofire.request(.POST, "http://httpbin.org/post", parameters: parameters)
下載一個檔案
Alamofire.download(.GET, "http://httpbin.org/stream/100", destination: { (temporaryURL, response) in if let directoryURL = NSFileManager.defaultManager() .URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as? NSURL { let pathComponent = response.suggestedFilename return directoryURL.URLByAppendingPathComponent(pathComponent) } return temporaryURL })
上傳檔案
let fileURL = NSBundle.mainBundle() .URLForResource("Default", withExtension: "png") Alamofire.upload(.POST, "http://httpbin.org/post", file: fileURL)
下載圖片
Alamofire.request(.GET, "/article/image/20150128/54c85e49bfa8d25764000f47/small_f3338d9cdf932cc3c0464dcb523361c5.jpg").response() {(_, _, data, _) in let image = UIImage(data: data! as NSData) self.imageView.image = image }
現在您已經學會了如何使用 Alamofire 操作最基本的網路請求了。
但是有可能因為 framework 的原因 在真機上執行失敗。千萬要淡定,請看下篇!!!