[快速学会Swift第三方库] Alamofire篇

简介: [快速学会Swift第三方库] Alamofire篇Alamofire是 Swift 语言的 HTTP 网络开发工具包,AFNetworking的 Swift 版,使用起来相当简单。目录快速学会Swift第三方库 Alamofire篇目录编码之前导入Alamofire其他操作Web请求示例代码运行结果数据请求JSON示

[快速学会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主页

目录
相关文章
|
9月前
|
缓存 JSON 安全
43 Swift中的一些第三方库
Swift中的一些第三方库
145 0
|
2月前
|
JSON 数据处理 Swift
【Swift 开发专栏】Swift 中的网络编程:URLSession 与 Alamofire
【4月更文挑战第30天】本文探讨了Swift中的网络编程,重点关注URLSession和Alamofire。URLSession是苹果提供的网络请求框架,允许底层控制和定制,适合需要高度灵活性的场景。Alamofire则是在URLSession基础上的第三方库,提供简洁接口和功能扩展,简化网络请求和错误处理。文中还介绍了两者在实际应用中的选择和使用场景,强调掌握网络编程基础的重要性。
|
Swift 数据安全/隐私保护 iOS开发
iOS开发 - swift通过Alamofire实现https通信
iOS开发 - swift通过Alamofire实现https通信
378 0
iOS开发 - swift通过Alamofire实现https通信
|
Swift
Swift - 不使用pods如何正确添加类似Alamofire这样的库
Swift - 不使用pods如何正确添加类似Alamofire这样的库
112 0
Swift - 不使用pods如何正确添加类似Alamofire这样的库
|
Swift
Swift - Alamofire简单GET和POST使用
Swift - Alamofire简单GET和POST使用
336 0
|
安全 iOS开发 Swift
Swift 网络访问库Alamofire 访问https localhost服务器
Alamofire提供了比IOS标准库便捷的网络访问接口,沿用了Objective-C的AFNetwork的各种优点,所以成为了我迁移到Swift平台不二的选择。
2452 0