Alamofire网址:http://cocoadocs.org/docsets/Alamofire/1.3.1/#source-file
使用:
请求
importAlamofire
Alamofire.request(.GET,"http://httpbin.org/get", parameters: ["foo":"bar"])
.response { request, response, data, errorin
println(request)
println(response)
println(error)
}
解析响应
数据序列化方法
response()
responseString(encoding: NSStringEncoding)
responseJSON(options: NSJSONReadingOptions)
responsePropertyList(options: NSPropertyListReadOptions)
返回字符串
Alamofire.request(.GET,"http://httpbin.org/get").responseString { _, _, string, _inprintln(string) }
返回JSON
Alamofire.request(.GET,"http://httpbin.org/get").responseJSON { _, _, JSON, _inprintln(JSON) }
链接响应处理
Alamofire.request(.GET,"http://httpbin.org/get").responseString { _, _, string, _inprintln(string) }.responseJSON { _, _, JSON, _inprintln(JSON) }
HTTP的几种请求方法
publicenumMethod:String{caseOPTIONS="OPTIONS"caseGET="GET"caseHEAD="HEAD"casePOST="POST"casePUT="PUT"casePATCH="PATCH"caseDELETE="DELETE"caseTRACE="TRACE"caseCONNECT="CONNECT"}
如下:
Alamofire.request(.POST,"http://httpbin.org/post")Alamofire.request(.PUT,"http://httpbin.org/put")Alamofire.request(.DELETE,"http://httpbin.org/delete")
参数
GET请求参数
Alamofire.request(.GET,"http://httpbin.org/get", parameters: ["foo":"bar"])// 或者可以:http://httpbin.org/get?foo=bar
POST请求参数
letparameters=["foo":"bar","baz": ["a",1],"qux": ["x":1,"y":2,"z":3]]Alamofire.request(.POST,"http://httpbin.org/post", parameters: parameters)// 或者可以:HTTP body: foo=bar&baz[]=a&baz[]=1&qux[x]=1&qux[y]=2&qux[z]=3
上传
支持上传的类型:
File 文件
Data 二进制数据
Stream 视频,音频
MultipartFormData表单数据
上传一个文件
letfileURL=NSBundle.mainBundle().URLForResource("Default", withExtension:"png")Alamofire.upload(.POST,"http://httpbin.org/post", file: fileURL)
上传文件且看得到进度
letfileURL=NSBundle.mainBundle().URLForResource("Default", withExtension:"png")
Alamofire.upload(.POST,"http://httpbin.org/post", file: fileURL)
.progress { bytesWritten, totalBytesWritten, totalBytesExpectedToWritein
println(totalBytesWritten)
}
.responseJSON { request, response, JSON, errorin
println(JSON)
}
Uploading MultipartFormData表单数据上传
Alamofire.upload(.POST, URLString:"http://httpbin.org/post", multipartFormData: { multipartFormDatainmultipartFormData.appendBodyPart(fileURL: unicornImageURL, name:"unicorn") multipartFormData.appendBodyPart(fileURL: rainbowImageURL, name:"rainbow") }, encodingCompletion: { encodingResultinswitchencodingResult {case.Success(letupload, _, _): upload.responseJSON { request, response, JSON, errorinprintln(JSON) }case.Failure(letencodingError): println(encodingError) } })
下载
支持下载的类型
Request
Resume Data
Downloading a File 下载文件
Alamofire.download(.GET,"http://httpbin.org/stream/100") { temporaryURL, responseinletfileManager=NSFileManager.defaultManager()ifletdirectoryURL=fileManager.URLsForDirectory(.DocumentDirectory, inDomains:.UserDomainMask)[0]as?NSURL {letpathComponent=response.suggestedFilenamereturndirectoryURL.URLByAppendingPathComponent(pathComponent!) }returntemporaryURL}
Using the Default Download Destination 下载文件到指定目录
//下载到document
letdestination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)
Alamofire.download(.GET,"http://img3.redocn.com/20101213/20101211_0e830c2124ac3d92718fXrUdsYf49nDl.jpg",destination: destination)
Downloading a File with Progress 下载文件且有进度
//下载到document
letdestination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)
Alamofire.download(.GET,"http://img3.redocn.com/20101213/20101211_0e830c2124ac3d92718fXrUdsYf49nDl.jpg", destination: destination).progress { bytesRead, totalBytesRead, totalBytesExpectedToReadin
println(totalBytesRead) //已读取的字节数
println(totalBytesExpectedToRead)//所有字节数
}
.response { request, response, _, errorin
println(response)
}
Caching 缓存
用系统的NSURLCache.去处理就行 了
注意点:(缺少白名单)
使用Alamofire框架请求网络会遇到请求的路径是正确的但是请求不到数据的问题,报错如下:
FAILURE: Error Domain=NSURLErrorDomain Code=-1022 "The resource could not be loaded because the App Transport Security policy requires the use of a secure connection."
原因:iOS9引入了新特性App Transport Security (ATS)。新特性要求App内访问的网络必须使用HTTPS协议。但是现在公司的项目使用的是HTTP协议,使用私有加密方式保证数据安全。现在也不能马上改成HTTPS协议传输。
解决办法:(添加白名单)
在Info.plist中添加NSAppTransportSecurity类型为Dictionary。
在NSAppTransportSecurity下添加NSAllowsArbitraryLoads类型Boolean,值设为YES.