[快速学会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,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("@R_502_159@ 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","id": 1,"id": 2,"id": 3,"id": 4,"id": 5,"id": 6,"origin": "202.115.52.205"}
深入学习
这里只列出了最常用的几种操作,如果你希望能够更加深入地学习Alamofire,可以前往GitHub-Alamofire主页 !