iOS开发——网络编程Swift篇&Alamofire详解

Alamofire详解

预览图

技术分享

Swift Alamofire 简介

技术分享

AlamofireSwift 语言的 HTTP 网络开发工具包,相当于Swift实现AFNetworking版本。

当然,AFNetworking非常稳定,在Mac OSX与iOS中也能像其他Objective-C代码一样用Swift编写。不过Alamofire更适合Swift语言风格习惯(Alamofire与AFNetworking可以共存一个项目中,互不影响).

Alamofire 取名来源于 Alamo Fire flower

Alamofire安装使用方法

使用CocoaPods安装,在podfile

1 source https://github.com/CocoaPods/Specs.git
2 platform :ios, 8.0
3 use_frameworks!
4 
5 pod Alamofire, ~> 1.2

 

submodule 方式安装 1 $ git submodule add https://github.com/Alamofire/Alamofire.git 

1.下载源码将Alamofire.xcodeproj拖拽至工程中如下图: 技术分享

2.工程->Build Phases->Target Dependencies 增加Alamofire 技术分享

3.点击如下图“+”按钮选择"New Copy Files Phase"添加,改名为“Copy Frameworks”并 选择选项下的“ Destination”为“ Frameworks”,然后添加“Alamofire.framework”

技术分享

4.在需要使用的swift文件中加入import Alamofire,如下图: 技术分享

功能

  • Chainable Request / Response methods
  • URL / JSON / plist Parameter Encoding
  • Upload File / Data / Stream
  • Download using Request or Resume data
  • Authentication with NSURLCredential
  • Progress Closure & NSProgress
  • cURL Debug Output

1.0版本计划

1.0版本将在Swift 1.0发布之后。

  • 100% Unit Test Coverage
  • Complete Documentation
  • HTTP Response Validation
  • TLS Chain Validation
  • UIKit / AppKit Extensions

环境要求

Xcode 6

iOS 7.0+ / Mac OS X 10.9+

Alamofire使用方法

GET 请求

 1 Alamofire.request(.GET, "http://httpbin.org/get") 

带参数

1 Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])

 

 

Response结果处理

1 Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
2          .response { (request, response, data, error) in
3                      println(request)
4                      println(response)
5                      println(error)
6                    }

 

Response结果字符串处理

1 Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
2          .responseString { (request, response, string, error) in
3                   println(string)
4          }

 

HTTP 方法(Medthods)

Alamofire.Method enum 列表出在RFC 2616中定义的HTTP方法 §9:

 1 public enum Method: String {
 2     case OPTIONS = "OPTIONS"
 3     case GET = "GET"
 4     case HEAD = "HEAD"
 5     case POST = "POST"
 6     case PUT = "PUT"
 7     case PATCH = "PATCH"
 8     case DELETE = "DELETE"
 9     case TRACE = "TRACE"
10     case CONNECT = "CONNECT"
11 }

 

这些值可以作为Alamofire.request请求的第一个参数.

1 Alamofire.request(.POST, "http://httpbin.org/post")
2 
3 Alamofire.request(.PUT, "http://httpbin.org/put")
4 
5 Alamofire.request(.DELETE, "http://httpbin.org/delete")

 

POST请求

1 let parameters = [
2     "foo": "bar",
3     "baz": ["a", 1],
4     "qux": [
5         "x": 1,
6         "y": 2,
7         "z": 3
8     ]
9 ]

 


 1 Alamofire.request(.POST, "http://httpbin.org/post", parameters: parameters) 

发送以下HttpBody内容:

 1 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

 1 enum ParameterEncoding {
 2     case URL
 3     case JSON(options: NSJSONWritingOptions)
 4     case PropertyList(format: NSPropertyListFormat,
 5                       options: NSPropertyListWriteOptions)
 6 
 7     func encode(request: NSURLRequest,
 8                 parameters: [String: AnyObject]?) ->
 9                     (NSURLRequest, NSError?)
10     { ... }
11 }

 

NSURLRequest方式编码参数

1 let URL = NSURL(string: "http://httpbin.org/get")
2 var request = NSURLRequest(URL: URL)
3 
4 let parameters = ["foo": "bar"]
5 let encoding = Alamofire.ParameterEncoding.URL
6 (request, _) = encoding.encode(request, parameters)

 

POST JSON格式数据

1 Alamofire.request(.POST, "http://httpbin.org/post", parameters: parameters, encoding: .JSON(options: nil))
2          .responseJSON {(request, response, JSON, error) in
3             println(JSON)
4          }

 

 

Response 方法

  • response()
  • responseString(encoding: NSStringEncoding)
  • responseJSON(options: NSJSONReadingOptions)
  • responsePropertyList(options: NSPropertyListReadOptions)

上传(Uploading)

支持的类型

  • File
  • Data
  • Stream
  • Multipart (Coming Soon)

上传文件

1 let fileURL = NSBundle.mainBundle()
2                       .URLForResource("Default",
3                                       withExtension: "png")
4 
5 Alamofire.upload(.POST, "http://httpbin.org/post", file: fileURL)

 

上传进度

1 Alamofire.upload(.POST, "http://httpbin.org/post", file: fileURL)
2         .progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in
3             println(totalBytesWritten)
4         }
5         .responseJSON { (request, response, JSON, error) in
6             println(JSON)
7         }

 

 

下载

支持的类型

  • Request
  • Resume Data

下载文件

 1 Alamofire.download(.GET, "http://httpbin.org/stream/100", destination: { (temporaryURL, response) in
 2     if let directoryURL = NSFileManager.defaultManager()
 3                           .URLsForDirectory(.DocumentDirectory,
 4                                             inDomains: .UserDomainMask)[0]
 5                           as? NSURL {
 6         let pathComponent = response.suggestedFilename
 7 
 8         return directoryURL.URLByAppendingPathComponent(pathComponent)
 9     }
10 
11     return temporaryURL
12 })

 

 

下载到默认路径

1 let destination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask)
2 
3 Alamofire.download(.GET, "http://httpbin.org/stream/100", destination: destination)

 

 

下载进度

1 Alamofire.download(.GET, "http://httpbin.org/stream/100", destination: destination)
2          .progress { (bytesRead, totalBytesRead, totalBytesExpectedToRead) in
3              println(totalBytesRead)
4          }
5          .response { (request, response, _, error) in
6              println(response)
7          }

 

 

认证(Authentication)

支持以下几种认证

  • HTTP Basic
  • HTTP Digest
  • Kerberos
  • NTLM

Http basic认证

1 let user = "user"
2 let password = "password"
3 
4 Alamofire.request(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)")
5     .authenticate(HTTPBasic: user, password: password)
6     .response {(request, response, _, error) in
7         println(response)
8         }

 

采用NSURLCredential&NSURLProtectionSpace方式认证

 1 let user = "user"
 2 let password = "password"
 3 
 4 let credential = NSURLCredential(user: user, password: password, persistence: .ForSession)
 5 let protectionSpace = NSURLProtectionSpace(host: "httpbin.org", port: 0, `protocol`: "https", realm: nil, authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
 6 
 7 
 8 
 9 Alamofire.request(.GET, "https://httpbin.org/basic-auth/\(user)/\(password)")
10     .authenticate(usingCredential: credential, forProtectionSpace: protectionSpace)
11     .response {(request, response, _, error) in
12         println(response)
13 }

 

Printable

1 let request = Alamofire.request(.GET, "http://httpbin.org/ip")
2 
3 println(request)
4 // GET http://httpbin.org/ip (200)

 

调试

1     let request = Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])
2 
3 debugPrintln(request)

 

Output (cURL)

1 $ curl -i 2     -H "User-Agent: Alamofire" 3     -H "Accept-Encoding: Accept-Encoding: gzip;q=1.0,compress;q=0.5" 4     -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" 5     "http://httpbin.org/get?foo=bar"

 

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。