[快速學會Swift第三方庫] Alamofire篇

究極死胖獸發表於2016-05-23

[快速學會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主頁

相關文章