著名的AFNetworking網絡基礎庫Swift版Alamofire
Swift Alamofire 簡介
Alamofire是 Swift 語言的 HTTP 網絡開發工具包,相當于Swift實現AFNetworking版本。
當然,AFNetworking非常穩定,在Mac OSX與iOS中也能像其他Objective-C代碼一樣用Swift編寫。不過Alamofire更適合Swift語言風格習慣(Alamofire與AFNetworking可以共存一個項目中,互不影響).
Alamofire 取名來源于 [Alamo Fire flower](https://aggie-horticulture.tamu.edu/wildseed/alamofire.html)
Alamofire安裝使用方法
使用CocoaPods安裝,在podfile
source 'https://github.com/CocoaPods/Specs.git' platform :ios, '8.0' use_frameworks! pod 'Alamofire', '~> 1.2'
submodule 方式安裝
$ git submodule add https://github.com/Alamofire/Alamofire.git
環境要求
Xcode 6
iOS 7.0+ / Mac OS X 10.9+
Alamofire使用方法
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)
}
Response結果字符串處理
Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
.responseString { (request, response, string, error) in
println(string)
}
HTTP 方法(Medthods)
Alamofire.Method enum 列表出在RFC 2616中定義的HTTP方法 §9:
public enum Method: String {
case OPTIONS = "OPTIONS"
case GET = "GET"
case HEAD = "HEAD"
case POST = "POST"
case PUT = "PUT"
case PATCH = "PATCH"
case DELETE = "DELETE"
case TRACE = "TRACE"
case CONNECT = "CONNECT"
}
這些值可以作為Alamofire.request請求的第一個參數.
Alamofire.request(.POST, "http://httpbin.org/post") Alamofire.request(.PUT, "http://httpbin.org/put") Alamofire.request(.DELETE, "http://httpbin.org/delete")
POST請求
let parameters = [
"foo": "bar",
"baz": ["a", 1],
"qux": [
"x": 1,
"y": 2,
"z": 3
]
]
Alamofire.request(.POST, "http://httpbin.org/post", parameters: parameters)
發送以下HttpBody內容:
foo=bar&baz[]=a&baz[]=1&qux[x]=1&qux[y]=2&qux[z]=3
Alamofire 使用Alamofire.ParameterEncoding可以支持URL query/URI form,JSON, PropertyList方式編碼參數。
Parameter Encoding
enum ParameterEncoding {
case URL
case JSON(options: NSJSONWritingOptions)
case PropertyList(format: NSPropertyListFormat,
options: NSPropertyListWriteOptions)
func encode(request: NSURLRequest,
parameters: [String: AnyObject]?) ->
(NSURLRequest, NSError?)
{ ... }
}
NSURLRequest方式編碼參數
let URL = NSURL(string: "http://httpbin.org/get") var request = NSURLRequest(URL: URL) let parameters = ["foo": "bar"] let encoding = Alamofire.ParameterEncoding.URL (request, _) = encoding.encode(request, parameters)
POST JSON格式數據
Alamofire.request(.POST, "http://httpbin.org/post", parameters: parameters, encoding: .JSON(options: nil))
.responseJSON {(request, response, JSON, error) in
println(JSON)
}
Response 方法
response() responseString(encoding: NSStringEncoding) responseJSON(options: NSJSONReadingOptions) responsePropertyList(options: NSPropertyListReadOptions)
上傳(Uploading)
支持的類型
File Data Stream Multipart (Coming Soon)
上傳文件
let fileURL = NSBundle.mainBundle()
.URLForResource("Default",
withExtension: "png")
Alamofire.upload(.POST, "http://httpbin.org/post", file: fileURL)
上傳進度
Alamofire.upload(.POST, "http://httpbin.org/post", file: fileURL)
.progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in
println(totalBytesWritten)
}
.responseJSON { (request, response, JSON, error) in
println(JSON)
}
下載
支持的類型
Request Resume Data
下載文件
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 destination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask) Alamofire.download(.GET, "http://httpbin.org/stream/100", destination: destination)
下載進度
Alamofire.download(.GET, "http://httpbin.org/stream/100", destination: destination)
.progress { (bytesRead, totalBytesRead, totalBytesExpectedToRead) in
println(totalBytesRead)
}
.response { (request, response, _, error) in
println(response)
}
認證(Authentication)
支持以下幾種認證
HTTP Basic HTTP Digest Kerberos NTLM
Http basic認證
let user = "user"
let password = "password"
Alamofire.request(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)")
.authenticate(HTTPBasic: user, password: password)
.response {(request, response, _, error) in
println(response)
}
采用NSURLCredential&NSURLProtectionSpace方式認證
let user = "user"
let password = "password"
let credential = NSURLCredential(user: user, password: password, persistence: .ForSession)
let protectionSpace = NSURLProtectionSpace(host: "httpbin.org", port: 0, `protocol`: "https", realm: nil, authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
Alamofire.request(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)")
.authenticate(usingCredential: credential, forProtectionSpace: protectionSpace)
.response {(request, response, _, error) in
println(response)
}
Printable
let request = Alamofire.request(.GET, "http://httpbin.org/ip") println(request) // GET http://httpbin.org/ip (200)
調試
let request = Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"]) debugPrintln(request)
Output (cURL)
$ curl -i \
-H "User-Agent: Alamofire" \
-H "Accept-Encoding: Accept-Encoding: gzip;q=1.0,compress;q=0.5" \
-H "Accept-Language: en;q=1.0,fr;q=0.9,de;q=0.8,zh-Hans;q=0.7,zh-Hant;q=0.6,ja;q=0.5" \
"http://httpbin.org/get?foo=bar"
更多的用法將會在接口文檔中一一列出,敬請期待。
Alamofire與AFNetworking是同一個作者
作者李剛是剛剛在線(www.superqq.com)站長,百度百家專欄作者 iOS工程師非著名自媒體,微信公眾號iOS開發:iOSDevTip運營者