(cocoapods需要更新版本金沙网址

三 HTTP相关:

public enum HTTPMethod: 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”

}

默认方法是 get

Alamofire.request(“”, method: .post)

Alamofire.request(“”, method: .put)

Alamofire.request(“”, method: .delete)

Alamofire 支持3种类型的参数编码:URL, JSON and
PropertyList。也可以自定义类型,需支持ParameterEncoding协议。

let headers: HTTPHeaders = [

“Authorization”: “Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==”,

“Accept”: “application/json”

]

Alamofire.request(“”, headers:
headers).responseJSON { response in

debugPrint

}

Alamofire SessionManager提供了默认的头部,内容如下:

•Accept-Encoding, which defaults to gzip;q=1.0, compress;q=0.5, per
RFC 7230 §4.2.3.

•Accept-Language, which defaults to up to the top 6 preferred
languages on the system, formatted like en;q=1.0, per RFC 7231 §5.3.5.

•User-Agent, which contains versioning information about the current
app. For example: iOS Example/1.0 (com.alamofire.iOS-Example; build:1;
iOS 10.0.0) Alamofire/4.0.0, per RFC 7231 §5.5.3.

如果需要自定义头部信息,需要这么来做:

If you need to customize these headers, a custom URLSessionConfiguration
should be created, the defaultHTTPHeaders property updated and the
configuration applied to a new SessionManager instance.

支持四种验证机制:

HTTP Basic HTTP Digest Kerberos NTLM

基本的用法:

let user = “user”

let password = “password”

Alamofire.request(“”)

.authenticate(user: user, password: password)

.responseJSON { response in

debugPrint

}

一 安装:

cocoapods的配置文件如下:(cocoapods需要更新版本,才支撑swift的第三方框架,更新的方法可以参考:CocoaPods1.1.1更新)

Podfile:

source ”

platform :ios, ‘10.0’

use_frameworks!

target ” do

pod ‘Alamofire’, ‘~> 4.0’

end

完成之后添加一下动态库,如下图:

金沙网址 1

四 Downloading Data to a File

Alamofire可以加载数据到内存缓存或者沙盒缓存,Alamofire.request用来将数据保存在内存中,这比较高效,但不适用于大文件的保存;使用Alamofire.download可以将大文件保存到应用的沙盒中。

Alamofire.download(” {
response in

if let data = response.result.value {

let image = UIImage(data: data)

}}

如果需要后台下载,需这样设置:

let configuration = URLSessionConfiguration.background(withIdentifier:
“com.example.app.background”)

let sessionManager = Alamofire.SessionManager(configuration:
configuration)

sessionManager.download(”
{ response in

if let data = response.result.value {

let image = UIImage(data: data)

}}

可以将文件从临时路径移动到目标路径:

let destination: DownloadRequest.DownloadFileDestination = { _, _ in

let documentsURL = FileManager.default.urls(for: .documentDirectory,
in: .userDomainMask)[0]

let fileURL = documentsURL.appendPathComponent(“pig.png”)

return (fileURL, [.removePreviousFile,
.createIntermediateDirectories])

}

Alamofire.download(urlString, to: destination).response { response in

print

if response.error == nil, let imagePath =
response.destinationURL?.path {

let image = UIImage(contentsOfFile: imagePath)

}}

也可以使用建议的路径:

let destination =
DownloadRequest.suggestedDownloadDestination(directory:
.documentDirectory)

Alamofire.download(“”, to: destination)

Alamofire.download(“”)

.downloadProgress { progress in

print(“Download Progress: \(progress.fractionCompleted)”)

}

.responseData { response in

if let data = response.result.value {

let image = UIImage(data: data)

}}

可以将下载的进程加入到一个GCD队列中:

let utilityQueue = DispatchQueue.global(qos: .utility)

Alamofire.download(“”)

.downloadProgress(queue: utilityQueue) { progress in

print(“Download Progress: \(progress.fractionCompleted)”)

}

.responseData { response in

if let data = response.result.value {

let image = UIImage(data: data)

}}

二 基础用法:

Alamofire 的网络操作都是异步进行(用response
handler)的,最基本的请求代码如下:

Alamofire.request(” { response
in

print(response.request) // original URL request

print(response.response) // HTTP URL response

print(response.data) // server data

print(response.result) // result of response serialization

if let JSON = response.result.value {

print(“JSON: \

}}

Alamofire 默认包含物种类型的response handlers:response responseString
responseJSON responseData

两种高级的方式:

1.Chained Response Handlers(链式,注意:会访问服务器数据多次)

Alamofire.request(“”)

.responseString { response in

print(“Response String: \(response.result.value)”)

}

.responseJSON { response in

print(“Response JSON: \(response.result.value)”)

}

It is important to note that using multiple response handlers on the
same Request requires the server data to be serialized multiple times.
Once for each response handler.

2.Response Handler Queue

Response handlers 默认是在主线程上运行的,可以添加到GCD队列中。

let utilityQueue = DispatchQueue.global(qos: .utility)

Alamofire.request(“:
utilityQueue) { response in

print(“Executing response handler on utility queue”)

}

Manual Validation

Alamofire.request(“”)

.validate(statusCode: 200..<300)

.validate(contentType: [“application/json”])

.responseData { response in

switch response.result {

case .success:

print(“Validation Successful”)

case .failure(let error):

print

}}

Automatic Validation

Automatically validates status code within 200…299 range, and that the
Content-Type header of the response matches the Accept header of the
request, if one is provided.

Alamofire.request(” {
response in

switch response.result {

case .success:

print(“Validation Successful”)

case .failure(let error):

print

}}

五 其他部分:

统计网络延时,响应时间等数据

Alamofire.request(” { response
in

print(response.timeline)

}

CustomStringConvertible

let request = Alamofire.request(“”)

print

// GET

CustomDebugStringConvertible

let request = Alamofire.request(“”, parameters:
[“foo”: “bar”])

debugPrint

参考代码

相关文章