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

 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 

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 请求

  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",
     ],
     "qux": [
         ,
         ,

     ]
 ]

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

发送以下HttpBody内容:

  foo=bar&baz[]=a&baz[]=&qux[x]=&qux[y]=&qux[z]= 

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)[]
                           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: , `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"
 

iOS开发——网络编程Swift篇&Alamofire详解的更多相关文章

  1. iOS开发——网络编程Swift篇&(八)SwiftyJSON详解

    SwiftyJSON详解 最近看了一些网络请求的例子,发现Swift在解析JSON数据时特别别扭,总是要写一大堆的downcast(as?)和可选(Optional),看?号都看花了.随后发现了这个库 ...

  2. iOS开发——网络编程Swift篇&(七)NSURLSession详解

    NSURLSession详解 // MARK: - /* 使用NSURLSessionDataTask加载数据 */ func sessionLoadData() { //创建NSURL对象 var ...

  3. iOS开发——网络编程Swift篇&(二)同/异&步请求

    同/异&步请求 同步: // MARK: - 同步请求 func httpSynchronousRequest() { //创建NSURL对象 var url:NSURL! = NSURL(s ...

  4. iOS开发——网络编程Swift篇&(一)网络监测

    网络监测 enum ReachabilityType { case WWAN, WiFi, NotConnected } public class Reachability { /** :see: O ...

  5. iOS开发——网络编程Swift篇&(六)异步Post方式

    异步Post方式 // MARK: - 异步Post方式 func asynchronousPost() { //创建NSURL对象 var url:NSURL! = NSURL(string: &q ...

  6. iOS开发——网络编程Swift篇&(五)同步Post方式

    同步Post方式 // MARK: - 同步Post方式 func synchronousPost() { //创建NSURL对象 var url:NSURL! = NSURL(string: &qu ...

  7. iOS开发——网络编程Swift篇&(四)异步Get方式

    异步Get方式 // MARK: - 异步Get方式 func asynchronousGet() { //创建NSURL对象 var url:NSURL! = NSURL(string: " ...

  8. iOS开发——网络编程Swift篇&(三)同步Get方式

    同步Get方式 // MARK: - 同步Get方式 func synchronousGet() { //创建NSURL对象 var url:NSURL! = NSURL(string: " ...

  9. iOS开发——网络编程OC篇&(一)XMPP简单介绍与准备

    XMPP简单介绍与准备 一.即时通讯简单介绍 1.简单说明 即时通讯技术(IM)支持用户在线实时交谈.如果要发送一条信息,用户需要打开一个小窗口,以便让用户及其朋友在其中输入信息并让交谈双方都看到交谈 ...

随机推荐

  1. Sharepoint学习笔记—习题系列--70-573习题解析 -(Q48-Q50)

    Question 48You create a user control named MySearchBox.ascx.You plan to change the native search con ...

  2. Emacs常用命令汇总

    注意:以下命令中标注的按键,大写的C代表Control,在键盘上通常是Ctrl键,而M代表Meta,在键盘上通常是Alt键,S则代表Shift,在键盘上通常是Shift键,也就是 C Control ...

  3. E/AndroidRuntime(1636): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.***.app.wx.MainActivity} : android.view.InflateException: Binary XML file line #51 :

    类中加载的xml中,所自定义组件的包名错误(xml中51行错误:自定义组件包名写错了).

  4. iOS加载程序视图的方式

    The UIViewController class provides built-in support for loading a view controller's views whenever ...

  5. vector,arraylist, linkedlist的区别是什么

    LinkedList类 LinkedList实现了List接口,允许null元素. 此外LinkedList提供额外的get,remove,insert方法在LinkedList的首部或尾部. Lin ...

  6. GCD中的dispatch_apply的用法及作用

    GCD中的dispatch_apply的用法及作用 (一)dispatch_apply的基本用法 dispatch_apply函数是dispatch_sync函数和Dispatch Group的关联A ...

  7. eclipse 中手动安装 subversive SVN

    为什么我选择手动安装呢?因为通过 eclipse market 下载实在太慢了.   1.下载离线安装包 http://www.eclipse.org/subversive/latest-releas ...

  8. js 毫秒 转 时间 日期 yyyy-mm-dd hh-mm-ss

    //格式化时间 var format = function(time, format){ var t = new Date(time); var tf = function(i){return (i ...

  9. poj 2942 Knights of the Round Table 圆桌骑士(双连通分量模板题)

    Knights of the Round Table Time Limit: 7000MS   Memory Limit: 65536K Total Submissions: 9169   Accep ...

  10. Linux 本地文件或文件夹上传服务器

    Linux 本地文件或文件夹上传服务器 一.权限设置 本地文件或文件夹上传服务器,你首先需要获取到root权限: 二.上传方式 上传方式有两种 : 1.通过 FTP 客户端上传文件或文件夹: 2.通过 ...