加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Alamofire-Swift Networking网络库

发布时间:2020-12-14 02:42:25 所属栏目:百科 来源:网络整理
导读:Alamofire 是Swift语言的 HTTP 网络开发工具包,相当于Swift实现AFNetworking版本。 当然,AFNetworking非常稳定,在Mac OSX与iOS中也能像其他Objective-C代码一样用Swift编写。不过Alamofire更适合Swift语言风格习惯(Alamofire与AFNetworking可以共存一个项目

Alamofire是Swift语言的 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")
带参数
"http://httpbin.org/get",parameters: ["foo": "bar"])
Response结果处理
"bar"])
         .response { (request,response,data,error) in
                     println(request)
                     println(response)
                     println(error)
                   }
Response结果字符串处理
"bar"])
         .responseString { (request,string,145)">in
                  println(string)
         }

HTTP 方法(Medthods)

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

public enum Method: String {
    case OPTIONS = "OPTIONS"
    GET = "GET"
    HEAD = "HEAD"
    POST = "POST"
    PUT = "PUT"
    PATCH = "PATCH"
    DELETE = "DELETE"
    TRACE = "TRACE"
    CONNECT = "CONNECT"
}

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

POST,22)">"http://httpbin.org/post")

PUT,22)">"http://httpbin.org/put")

DELETE,22)">"http://httpbin.org/delete")

POST请求

let parameters = [
    "bar",22)">"baz": ["a",1],22)">"qux": [
        "x": 1,22)">"y": 2,22)">"z": 3
    ]
]

"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
ParameterEncoding {
    URL
    JSON(options: NSJSONWritingOptions)
    PropertyList(format: NSPropertyListFormat,options: NSPropertyListWriteOptions)

    func encode(request: NSURLRequest,parameters: [String: AnyObject]?) ->
                    (NSError?)
    { ... }
}
NSURLRequest方式编码参数
let URL = NSURL(string: "http://httpbin.org/get")
var request = NSURLRequest(URL: URL)

let parameters = ["bar"]
let encoding = Alamofire.ParameterEncoding.URL
(request,207)">_) = encoding.encode(request,parameters)
POST JSON格式数据
JSON(options: nil))
         .responseJSON {(request,153)">JSON,145)">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(. 上传进度 
println(totalBytesWritten)
        }
        .responseJSON { (request,153)">JSON)
        }

下载

  • Request
  • Resume Data
  • 下载文件
    Alamofire.download(."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 = Request.suggestedDownloadDestination(directory: .UserDomainMask)
    
    下载进度 
    
    in
                 println(totalBytesRead)
             }
             .response { (request,207)">_,153)">println(response)
             }

    认证(Authentication)

    支持以下几种认证
    • HTTP Basic
    • HTTP Digest
    • Kerberos
    • NTLM
    Http basic认证
    let user = "user"
    let password = "password"
    
    "https://httpbin.org/basic-auth/(user)/(password)")
        .authenticate(HTTPBasic: user,password: password)
        .response {(request,145)">in
            println(response)
            }
    采用NSURLCredential&NSURLProtectionSpace方式认证
    "password"
    
    let credential = NSURLCredential(user: user,password: password,persistence: .ForSession)
    let protectionSpace = NSURLProtectionSpace(host: "httpbin.org",port: 0,`protocol`: "https",realm: nil,153)">authenticationMethod: NSURLAuthenticationMethodHTTPBasic) Alamofire.request(.https://httpbin.org/basic-auth/(user)/(password)") .authenticate(usingCredential: credential,153)">forProtectionSpace: protectionSpace) .response {(request,153)">println(response)
    }

    Printable

    let request = "http://httpbin.org/ip")
    
    println(request)
    // GET http://httpbin.org/ip (200)

    调试

    "bar"])
    
    debugPrintln(request)

    Output (cURL)

    $ curl -i 
        -H "User-Agent: Alamofire" 
        -"Accept-Encoding: Accept-Encoding: gzip;q=1.0,compress;q=0.5" 
        -"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是同一个作者

    (编辑:李大同)

    【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

      推荐文章
        热点阅读