Alamofire-Swift Networking网络库

Alamofire-Swift Networking网络库,第1张

概述预览图 Swift Alamofire 简介 Alamofire是 Swift 语言的 HTTP 网络开发工具包,相当于Swift实现AFNetworking版本。 当然,AFNetworking非常稳定,在Mac OSX与iOS中也能像其他Objective-C代码一样用Swift编写。不过Alamofire更适合Swift语言风格习惯(Alamofire与AFNetworking可以共存一个项 预览图 Swift Alamofire 简介

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")
带参数
Alamofire.request(.GET,"http://httpbin.org/get",parameters: ["foo": "bar"])
Response结果处理
Alamofire.request(.GET,parameters: ["foo": "bar"])         .response { (request,response,data,error) in                     println(request)                     println(response)                     println(error)                   }
Response结果字符串处理
Alamofire.request(.GET,parameters: ["foo": "bar"])         .responseString { (request,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,parameters: parameters,enCoding: .JsON(options: nil))         .responseJsON {(request,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,file: fileURL)
上传进度
Alamofire.upload(.POST,file: fileURL)        .progress { (bytesWritten,totalBytesWritten,totalBytesExpectedToWrite) in            println(totalBytesWritten)        }        .responseJsON { (request,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,destination: destination)
下载进度
Alamofire.download(.GET,destination: destination)         .progress { (bytesRead,totalBytesRead,totalBytesExpectedToRead) in             println(totalBytesRead)         }         .response { (request,_,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,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,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,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是同一个作者

总结

以上是内存溢出为你收集整理的Alamofire-Swift Networking网络库全部内容,希望文章能够帮你解决Alamofire-Swift Networking网络库所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/1080776.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-27
下一篇2022-05-27

发表评论

登录后才能评论

评论列表(0条)

    保存