swift - Alamofire 网络请求

Alamofire是一个swift语言的网络开源库,主要用于网络请求,响应操作,响应校验,响应缓存
其基本用法如下:
进行网络请求、响应操作、响应校验、响应缓存
http方式、parameter编码、http headers 、验证
数据的上传与下载
工具类有CURL command outPut、statical metrics
高级用法
url 绘话管理、绘话代理、绘话请求
routing请求操作
model objects
安全已经网络监测

例子一、一个简单的网络请求
Alamofire.request("https://httpbin.org/getdata").responseJSON{ response in
// 这是一个简单的网络请求,采用的是get请求
/*response常用的几个属性
* request 原url请求
*response httpurl的响应
*result 序列化的操作
*/
print("Request: \(String(describing: response.request))") // 打印请求的URL
print("Response: \(String(describing: response.response))") //打印请求的响应
print("Result: \(response.result)") //打印返回的序列化内容
if let json = response.result.value {
//序列化后的内容 主要输出的是json内容格式
}

if let data = response.data let utf8 = String(data:data, encoding:.utf8) {
// 以二进制数据进行输出,主要用于进行缓存
}
}
Alamofire 一共包含了5中不同的响应方式
第一种 返回response对象
func response( queue: DispatchQueue?, completionHandler: @escaping (DefaultDataResponse) -> Void) -> Self
第二种 返回data数据
func responseData( queue: DispatchQueue?, completionHandler: @escaping (DataResponse<Data>) -> Void) -> Self
第三种 返回string
func responseString( queue: DispatchQueue?, encoding: String.Encoding?, completionHandler: @escaping (DataResponse<String>) -> Void) -> Self
第四种返回json
func responseJSON( queue: DispatchQueue?, completionHandler: @escaping (DataResponse<Any>) -> Void) -> Self
第五种 返回list
func responsePropertyList( queue: DispatchQueue?, completionHandler: @escaping (DataResponse<Any>) -> Void)) -> Self
一、response 仅仅用于响应请求操作,仅仅是进行执行请求
Alamofire.request("https://httpbin.org/get").response { response in print("Request: \(response.request)") print("Response: \(response.response)") print("Error: \(response.error)") if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) { print("Data: \(utf8Text)") }}

二、responseData 用于进行响应数据操作
Alamofire.request("https://httpbin.org/get").responseData { response in debugPrint("All Response Info: \(response)")// value是data数据 if let data = response.result.value, let utf8Text = String(data: data, encoding: .utf8) { print("Data: \(utf8Text)") }}
responseString 用于字符串响应处理
Alamofire.request("https://httpbin.org/get").responseString { response in
vale是string数据 print("Success: \(response.result.isSuccess)") print("Response String: \(response.result.value)")}
responseJSON 用于返回json数据
Alamofire.request("https://httpbin.org/get").responseJSON { response in debugPrint(response)// value是任意类型数据 if let json = response.result.value { print("JSON: \(json)") }}
请求链接响应时的操作
Alamofire.request("https://httpbin.org/get") .responseString { response in print("Response String: \(response.result.value)") } .responseJSON { response in print("Response JSON: \(response.result.value)") }
响应线程
// 创建一个队列,队列中有线程
let utilityQueue = DispatchQueue.global(qos: .utility)Alamofire.request("https://httpbin.org/get").responseJSON(queue: utilityQueue) { response in
// 在线程种去执行此操作 print("Executing response handler on utility queue")}

手动的去响应校验
Alamofire.request("https://httpbin.org/get") .validate(statusCode: 200..<300) 200- 300之间的字节,将要校验的字节 .validate(contentType: ["application/json"]) 内容格式为json .responseData { response in switch response.result { case .success: print("Validation Successful") case .failure(let error): print(error) } }
自动响应校验
Alamofire.request("https://httpbin.org/get").validate().responseJSON { response in switch response.result { case .success: print("Validation Successful") case .failure(let error): print(error) }}

http的请求方法
public enum HTTPMethod: String { case options = "OPTIONS" case get = "GET" // get case head = "HEAD" case post = "POST" //post case put = "PUT" case patch = "PATCH" case delete = "DELETE" case trace = "TRACE" case connect = "CONNECT" // 长链接}
例如:
Alamofire.request("https://httpbin.org/post", method: .post) //进行的post请求操作
Alamofire.request("https://httpbin.org/put", method: .put)// put 请求操作

参数编码格式
url的编码格式
let parameters: Parameters = ["foo": "bar"] 编码格式为foo与bar// All three of these calls are equivalentAlamofire.request("https://httpbin.org/get", parameters: parameters) // encoding defaults to `URLEncoding.default`Alamofire.request("https://httpbin.org/get", parameters: parameters, encoding: URLEncoding.default)Alamofire.request("https://httpbin.org/get", parameters: parameters, encoding: URLEncoding(destination: .methodDependent))

// post请求的编码格式
let parameters: Parameters = [ "foo": "bar", "baz": ["a", 1], "qux": [ "x": 1, "y": 2, "z": 3 ]]// All three of these calls are equivalentAlamofire.request("https://httpbin.org/post", method: .post, parameters: parameters)Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: URLEncoding.default)Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: URLEncoding.httpBody)

json的编码格式
let parameters: Parameters = [ "foo": [1,2,3], "bar": [ "baz": "qux" ]]// Both calls are equivalentAlamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: JSONEncoding.default)Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: JSONEncoding(options: []))

自定义的编码格式
// 自定义的编码
struct JSONStringArrayEncoding: ParameterEncoding { private let array: [String] init(array: [String]) { self.array = array } func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { var urlRequest = try urlRequest.asURLRequest() let data = try JSONSerialization.data(withJSONObject: array, options: []) if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") } urlRequest.httpBody = data return urlRequest }}

http的headers
let headers: HTTPHeaders = [ "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", //授权 "Accept": "application/json" // 接受]Alamofire.request("https://httpbin.org/headers", headers: headers).responseJSON { response in debugPrint(response)}

例如:含账户和密码的授权请求
let user = "user"let password = "password"
Alamofire.request("https://httpbin.org/basic-auth/\(user)/\(password)") .authenticate(user: user, password: password) .responseJSON { response in debugPrint(response) }

let user = "user"let password = "password"var headers: HTTPHeaders = [:] /空字典
if let authorizationHeader = Request.authorizationHeader(user: user, password: password) { headers[authorizationHeader.key] = authorizationHeader.value}
Alamofire.request("https://httpbin.org/basic-auth/user/password", headers: headers) .responseJSON { response in debugPrint(response) }

url请求证书的授权
let user = "user"let password = "password"
let credential = URLCredential(user: user, password: password, persistence: .forSession)
Alamofire.request("https://httpbin.org/basic-auth/\(user)/\(password)") .authenticate(usingCredential: credential) .responseJSON { response in debugPrint(response) }

下载一个data到文件
Alamofire.download("https://httpbin.org/image/png").responseData { response in if let data = response.result.value { let image = UIImage(data: data) }}
下载进度显示
Alamofire.download("https://httpbin.org/image/png") .downloadProgress { progress in print("Download Progress: \(progress.fractionCompleted)")
// 下载的完成进度 } .responseData { response in if let data = response.result.value { let image = UIImage(data: data) } }
与线程关联的下载进度
let utilityQueue = DispatchQueue.global(qos: .utility)Alamofire.download("https://httpbin.org/image/png") .downloadProgress(queue: utilityQueue) { progress in print("Download Progress: \(progress.fractionCompleted)") } .responseData { response in if let data = response.result.value { let image = UIImage(data: data) } }

更新data到服务器
let imageData = UIPNGRepresentation(image)!
Alamofire.upload(imageData, to: "https://httpbin.org/post").responseJSON { response in debugPrint(response)}

跟新文件
let fileURL = Bundle.main.url(forResource: "video", withExtension: "mov")
Alamofire.upload(fileURL, to: "https://httpbin.org/post").responseJSON { response in debugPrint(response)}
更新可变数据
Alamofire.upload( multipartFormData: { multipartFormData in multipartFormData.append(unicornImageURL, withName: "unicorn") multipartFormData.append(rainbowImageURL, withName: "rainbow") }, to: "https://httpbin.org/post", encodingCompletion: { encodingResult in switch encodingResult { case .success(let upload, _, _): upload.responseJSON { response in debugPrint(response) } case .failure(let encodingError): print(encodingError) } })
更新进度
let fileURL = Bundle.main.url(forResource: "video", withExtension: "mov")
Alamofire.upload(fileURL, to: "https://httpbin.org/post")
// 更新进度 .uploadProgress { progress in // main queue by default print("Upload Progress: \(progress.fractionCompleted)") }
// 下载进度 .downloadProgress { progress in // main queue by default print("Download Progress: \(progress.fractionCompleted)") }
// 是否完成 .responseJSON { response in debugPrint(response) }


高级应用
请求协议管理
Alamofire.request("https://httpbin.org/get")
相等于
let sessionManager = Alamofire.SessionManager.default
sessionManager.request("https://httpbin.org/get")

默认配置创建sessionManager
let configuration = URLSessionConfiguration.default
let sessionManager = Alamofire.SessionManager(configuration: configuration)
后台任务
let configuration = URLSessionConfiguration.background(withIdentifier: "com.example.app.background")
let sessionManager = Alamofire.SessionManager(configuration: configuration)
暂时任务
let configuration = URLSessionConfiguration.ephemeral
let sessionManager = Alamofire.SessionManager(configuration: configuration)

配置session
var defaultHeaders = Alamofire.SessionManager.defaultHTTPHeadersdefaultHeaders["DNT"] = "1 (Do Not Track Enabled)"// http dnt设置
let configuration = URLSessionConfiguration.defaultconfiguration.httpAdditionalHeaders = defaultHeaders
let sessionManager = Alamofire.SessionManager(configuration: configuration)

sessionManager的代理
let sessionManager = Alamofire.SessionManager(configuration: URLSessionConfiguration.default)
let delegate: Alamofire.SessionDelegate = sessionManager.delegate
delegate.taskWillPerformHTTPRedirection = { session, task, response, request in var finalRequest = request if let originalRequest = task.originalRequest, let urlString = originalRequest.url?.urlString, urlString.contains("apple.com") { finalRequest = originalRequest } return finalRequest}

阅读更多
个人分类: oc基础
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭