著名的AFNetworking网络基础库Swift版Alamofire
jopen
9年前
<p><a href="/misc/goto?guid=4958851213782329914" target="_blank">源代码</a> </p> <p href="https://simg.open-open.com/show/3be6b214272b2778f4f0a758964dccea.gif"><img alt="著名的AFNetworking网络基础库Swift版Alamofire" src="https://simg.open-open.com/show/3be6b214272b2778f4f0a758964dccea.gif" width="369" height="648" /> </p> <h2>Swift Alamofire 简介 </h2> <p href="https://simg.open-open.com/show/aa4382121a7983d8b102b05d2c3c0fcb.png"><img alt="著名的AFNetworking网络基础库Swift版Alamofire" src="https://simg.open-open.com/show/aa4382121a7983d8b102b05d2c3c0fcb.png" width="700" height="205.88235294117646" /> </p> <p>Alamofire是 Swift 语言的 HTTP 网络开发工具包,相当于Swift实现<a href="/misc/goto?guid=4958968172213038536">AFNetworking</a>版本。 </p> <p>当然,AFNetworking非常稳定,在Mac OSX与iOS中也能像其他Objective-C代码一样用Swift编写。不过Alamofire更适合Swift语言风格习惯(Alamofire与AFNetworking可以共存一个项目中,互不影响). </p> <pre class="brush:cpp; toolbar: true; auto-links: false;">Alamofire 取名来源于 [Alamo Fire flower](https://aggie-horticulture.tamu.edu/wildseed/alamofire.html)</pre> <h2>Alamofire安装使用方法 </h2> <p>使用CocoaPods安装,在podfile </p> <pre class="brush:cpp; toolbar: true; auto-links: false;">source 'https://github.com/CocoaPods/Specs.git' platform :ios, '8.0' use_frameworks! pod 'Alamofire', '~> 1.2'</pre> <p>submodule 方式安装 </p> <pre class="brush:cpp; toolbar: true; auto-links: false;">$ git submodule add https://github.com/Alamofire/Alamofire.git</pre> <h2>环境要求 </h2> <p>Xcode 6 </p> <p>iOS 7.0+ / Mac OS X 10.9+ </p> <h2>Alamofire使用方法 </h2> <h3>GET 请求 </h3> <pre class="brush:cpp; toolbar: true; auto-links: false;">Alamofire.request(.GET, "http://httpbin.org/get")</pre> <p>带参数 </p> <pre class="brush:cpp; toolbar: true; auto-links: false;">Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"])</pre> <p>Response结果处理 </p> <pre class="brush:cpp; toolbar: true; auto-links: false;">Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"]) .response { (request, response, data, error) in println(request) println(response) println(error) }</pre> <p>Response结果字符串处理 </p> <pre class="brush:cpp; toolbar: true; auto-links: false;">Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"]) .responseString { (request, response, string, error) in println(string) }</pre> <h2>HTTP 方法(Medthods) </h2> <p>Alamofire.Method enum 列表出在RFC 2616中定义的HTTP方法 §9: </p> <pre class="brush:cpp; toolbar: true; auto-links: false;">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" }</pre> <p>这些值可以作为Alamofire.request请求的第一个参数. </p> <pre class="brush:cpp; toolbar: true; auto-links: false;">Alamofire.request(.POST, "http://httpbin.org/post") Alamofire.request(.PUT, "http://httpbin.org/put") Alamofire.request(.DELETE, "http://httpbin.org/delete")</pre> <p>POST请求 </p> <pre class="brush:cpp; toolbar: true; auto-links: false;">let parameters = [ "foo": "bar", "baz": ["a", 1], "qux": [ "x": 1, "y": 2, "z": 3 ] ] Alamofire.request(.POST, "http://httpbin.org/post", parameters: parameters)</pre> <p>发送以下HttpBody内容: </p> <pre class="brush:cpp; toolbar: true; auto-links: false;">foo=bar&baz[]=a&baz[]=1&qux[x]=1&qux[y]=2&qux[z]=3</pre> <p>Alamofire 使用Alamofire.ParameterEncoding可以支持URL query/URI form,JSON, PropertyList方式编码参数。 </p> <p>Parameter Encoding </p> <pre class="brush:cpp; toolbar: true; auto-links: false;">enum ParameterEncoding { case URL case JSON(options: NSJSONWritingOptions) case PropertyList(format: NSPropertyListFormat, options: NSPropertyListWriteOptions) func encode(request: NSURLRequest, parameters: [String: AnyObject]?) -> (NSURLRequest, NSError?) { ... } }</pre> <p>NSURLRequest方式编码参数 </p> <pre class="brush:cpp; toolbar: true; auto-links: false;">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)</pre> <p>POST JSON格式数据 </p> <pre class="brush:cpp; toolbar: true; auto-links: false;">Alamofire.request(.POST, "http://httpbin.org/post", parameters: parameters, encoding: .JSON(options: nil)) .responseJSON {(request, response, JSON, error) in println(JSON) }</pre> <p>Response 方法 </p> <pre class="brush:cpp; toolbar: true; auto-links: false;">response() responseString(encoding: NSStringEncoding) responseJSON(options: NSJSONReadingOptions) responsePropertyList(options: NSPropertyListReadOptions)</pre> <h3>上传(Uploading) </h3> <p>支持的类型 </p> <pre class="brush:cpp; toolbar: true; auto-links: false;">File Data Stream Multipart (Coming Soon)</pre> <p>上传文件 </p> <pre class="brush:cpp; toolbar: true; auto-links: false;">let fileURL = NSBundle.mainBundle() .URLForResource("Default", withExtension: "png") Alamofire.upload(.POST, "http://httpbin.org/post", file: fileURL)</pre> <h3>上传进度 </h3> <pre class="brush:cpp; toolbar: true; auto-links: false;">Alamofire.upload(.POST, "http://httpbin.org/post", file: fileURL) .progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in println(totalBytesWritten) } .responseJSON { (request, response, JSON, error) in println(JSON) }</pre> <h3>下载 </h3> <p>支持的类型 </p> <pre class="brush:cpp; toolbar: true; auto-links: false;">Request Resume Data</pre> <p>下载文件 </p> <pre class="brush:cpp; toolbar: true; auto-links: false;">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 })</pre> <p>下载到默认路径 </p> <pre class="brush:cpp; toolbar: true; auto-links: false;">let destination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .UserDomainMask) Alamofire.download(.GET, "http://httpbin.org/stream/100", destination: destination)</pre> <p>下载进度 </p> <pre class="brush:cpp; toolbar: true; auto-links: false;">Alamofire.download(.GET, "http://httpbin.org/stream/100", destination: destination) .progress { (bytesRead, totalBytesRead, totalBytesExpectedToRead) in println(totalBytesRead) } .response { (request, response, _, error) in println(response) }</pre> <h3>认证(Authentication) </h3> <p>支持以下几种认证 </p> <pre class="brush:cpp; toolbar: true; auto-links: false;">HTTP Basic HTTP Digest Kerberos NTLM</pre> <p>Http basic认证 </p> <pre class="brush:cpp; toolbar: true; auto-links: false;">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) }</pre> <p>采用NSURLCredential&NSURLProtectionSpace方式认证 </p> <pre class="brush:cpp; toolbar: true; auto-links: false;">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) }</pre> <h3>Printable </h3> <pre class="brush:cpp; toolbar: true; auto-links: false;">let request = Alamofire.request(.GET, "http://httpbin.org/ip") println(request) // GET http://httpbin.org/ip (200)</pre> <h3>调试 </h3> <pre class="brush:cpp; toolbar: true; auto-links: false;">let request = Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["foo": "bar"]) debugPrintln(request)</pre> <h3>Output (cURL) </h3> <pre class="brush:cpp; toolbar: true; auto-links: false;">$ 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"</pre> <p>更多的用法将会在接口文档中一一列出,敬请期待。 </p> <p>Alamofire与AFNetworking是同一个作者 </p> <blockquote> <p>作者李刚是刚刚在线(www.superqq.com)站长,百度百家专栏作者 iOS工程师非著名自媒体,微信公众号iOS开发:iOSDevTip运营者 </p> </blockquote> <p href="https://simg.open-open.com/show/12cc8408fdc3820e7760279d185139ae.png"><img alt="iOSDevTip" src="https://simg.open-open.com/show/12cc8408fdc3820e7760279d185139ae.png" width="600" height="300" /> </p>