Alamofire-使用
所有类型请求,Alamofire
都直接提供,通过Alamofire
直接调用,配置相关参数即可。示例如下:
1、GET请求
let urlStr = "http://onapp.yahibo.top/public/?s=api/test/list"
Alamofire.request(url).responseJSON { (response) inswitch response.result {case .success(let json):print(json)breakcase .failure(let error):print("error:\(error)")break}
}
url
支持多种类型,String、URL、Request
,在框架内部已经为我们处理好了,怎么方便怎么用- 直接调用
responseJSON
获取json
数据
request的参数如下:
public func request(_ url: URLConvertible,method: HTTPMethod = .get,parameters: Parameters? = nil,encoding: ParameterEncoding = URLEncoding.default,headers: HTTPHeaders? = nil)
- 默认不设置请求方法为
get
方法,因此使用中get
方法,不需要配置直接通过url
发起请求 - 参数
Parameters
为字典类型,默认为空,会根据method
做不同处理
2、POST请求
let urlStr = "http://onapp.yahibo.top/public/?s=api/test/list"
Alamofire.request(url, method: .post, parameters: ["name":"hibo","password":"123456"]).responseJSON { (response) inswitch response.result {case .success(let json):print(json)breakcase .failure(let error):print("error:\(error)")break}
}
- 需要设置
method
参数为post
3、文件下载
let videoUrl = "http://onapp.yahibo.top/public/videos/video.mp4"
Alamofire.download(videoUrl, to: { (videoUrl, response) -> (destinationURL: URL, options: DownloadRequest.DownloadOptions) inlet documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]let time = Date().timeIntervalSince1970let fileURL = documentsURL.appendingPathComponent("\(time).mp4")print("沙盒路径:\(documentsURL)")return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}).downloadProgress { (progress) inprint(progress)
}
- 获取沙盒路径转存视频文件
4、上传表单
let imgArr:Array = [UIImage.init(named: "headimg"),UIImage.init(named: "headimg")]
Alamofire.upload(multipartFormData: { (formData) informData.append("hibo".data(using: .utf8)!, withName: "name")formData.append("123456".data(using: .utf8)!, withName: "password")for i in 0 ... imgArr.count-1 {let data = imgArr[i]!.pngData()let fileName = "image_\(i).png"formData.append(data!, withName: "image[]", fileName: fileName, mimeType: "image/png")}
}, to: url) { (result) inswitch result {case .success(let upload, _, _):upload.uploadProgress(closure: { (progress) inprint(progress)}).responseJSON(completionHandler: { (response) inswitch response.result {case .success(let json):print(json)breakcase .failure(let error):print("error:\(error)")break}})breakcase .failure(let error):print(error)break}print("result:\(result)")
}
- 能够同时上传其他参数和图片
image[]
后台通过image获取到的是一个数组fileName
图片名称- 在
result
中监听上传进度,获取上传结果
5、后台下载
设置全局对象:
struct BackgroundManager {static let shared = BackgroundManager()let manager: SessionManager = {let configuration = URLSessionConfiguration.background(withIdentifier:"com.yahibo.background_id")configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeadersreturn SessionManager(configuration: configuration)}()
}
调用发起下载请求:
BackgroundManager.shared.manager.download(url) { (url, response) -> (destinationURL: URL, options: DownloadRequest.DownloadOptions) inlet documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]let fileURL = documentsURL.appendingPathComponent("\(self.currentDateStr()).mp4")return (fileURL, [.removePreviousFile, .createIntermediateDirectories])}.downloadProgress(queue: DispatchQueue.global(qos: .utility)) { (progress) inprint(progress)}.response(queue: DispatchQueue.global(qos: .utility), completionHandler: { (response) inprint("完成下载:\(response)")})
开启后台下载权限并赋值系统闭包:
//设置此处开启后台下载权限
func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void) {BackgroundManager.shared.manager.backgroundCompletionHandler = completionHandler
}
后台下载与其他请求不同,需要开启权限,并将系统闭包传递到请求代理方法中,后台下载完成,通过闭包通知系统及时刷新界面。
manager
设置为全局变量为方便调用。
6、设置公共参数
实现RequestAdapter协议方法
class MyAdapter: RequestAdapter{func adapt(_ urlRequest: URLRequest) throws -> URLRequest {var request = urlRequestrequest.setValue("hibotoken", forHTTPHeaderField: "token")request.setValue("device", forHTTPHeaderField: "iOS")request.setValue("vision", forHTTPHeaderField: "1.0.0")return request}
}
- 创建
MyAdapter
类继承协议,并实现协议方法 - 设置开发中使用到的公共参数
设置属性
let url = "http://onapp.yahibo.top/public/?s=api/test/list”
Alamofire.SessionManager.default.adapter = MyAdapter()
Alamofire.request(url).responseJSON { (response) inswitch response.result {case .success(let json):print(json)breakcase .failure(let error):print("error:\(error)")break}
}
这里的default
是个单列,属性设置一次就好,不用在每次请求前设置。
7、请求重定向
实现RequestAdapter协议方法
class redireatAdapter: RequestAdapter{func adapt(_ urlRequest: URLRequest) throws -> URLRequest {let newURLRequest = URLRequest.init(url: URL.init(string: "http://onapp.yahibo.top/public/?s=api/test")!)return newURLRequest}
}
- 重新设置了请求
URLRequest
对象,改变了请求url
设置属性
let url = "http://onapp.yahibo.top/public/?s=api/test/list”
Alamofire.SessionManager.default.adapter = redireatAdapter()
Alamofire.request(url).responseJSON { (response) inswitch response.result {case .success(let json):print(json)breakcase .failure(let error):print("error:\(error)")break}
}
该重定向不常用,如应用被逆向,给个重定向,就是不给你数据。
8、重新请求
同上面协议,创建子类实现方法,调用即可。
实现协议方法
class MyRetrier: RequestRetrier{var count: Int = 0func should(_ manager: SessionManager, retry request: Request, with error: Error, completion: @escaping RequestRetryCompletion) {if count<3 {completion(true,2)count += 1}else{completion(false,2)}}
}
- 设定重新发送请求3次
- 延时2秒再发送请求
设置属性
Alamofire.SessionManager.default.retrier = MyRetrier()
请求失败后,就会隔时重新发送请求。
9、自定义验证
let urlStr = "http://onapp.yahibo.top/public/?s=api/test/list2"
let url = URL.init(string: urlStr)!
Alamofire.SessionManager.default.retrier = MyRetrier()
Alamofire.request(url).responseJSON {(response) in
switch response.result{case .success(let json):print("json:\(json)")break
case .failure(let error):print("error:\(error)")break
}
}.validate{ (request, response, data) -> Request.ValidationResult inprint(response)guard let _ = data else {return .failure(NSError(domain: "没有数据啊", code: 10086, userInfo: nil))}if response.statusCode == 404 {return .failure(NSError(domain: "密码错误", code: response.statusCode, userInfo: nil))}return .success
}
调用
validate
方法,实现参数闭包,在闭包内拦截错误消息。
我使用该框架,可能会对框架进一步封装,对错误响应统一处理,如错误消息,通过弹框通知用户,处理loading
视图。不知道大佬们都怎么处理。
Alamofire-使用相关推荐
- Swift - 使用Alamofire通过HTTPS进行网络请求,及证书的使用
(本文代码已升级至Swift3) 我原来写过一篇文章介绍如何使用证书通过SSL/TLS方式进行网络请求(Swift - 使用URLSession通过HTTPS进行网络请求,及证书的使用),当时用的是 ...
- swift集成alamofire的简单封装
import UIKit import Alamofire enum MethodType{ case GET case POST } class NetworkTool: NSObject { cl ...
- Swift 3.0封装 URLSession 的GET/SET方法代替 Alamofire
升级到 Swift3.0 之后,新版本的 Alamofire 只支持 iOS 9.0 以上的系统,如果要适配 iOS 8,需要自己封装 URLSession,下面是笔者的方案: 这里使用的是 Swif ...
- Swift: 用Alamofire做http请求,用ObjectMapper解析JSON
示例代码看最后. 跟不上时代的人突然间走在了时代的前列,果然有别样的风景.首先鄙视一下AFNetworking.这个东西实在太难用了.不想封装都不行,要不写一大堆代码. NSURL *URL = [N ...
- ALDownloadManager 基于Alamofire封装的下载器
ALDownloadManager包含了断点续传,多文件顺序下载,多文件同时下载 同时下载 顺序下载 外层调用: 单文件下载 ALDownloadManager.shared.download(url ...
- Alamofire源码解读系列(九)之响应封装(Response)
本篇主要带来Alamofire中Response的解读 前言 在每篇文章的前言部分,我都会把我认为的本篇最重要的内容提前讲一下.我更想同大家分享这些顶级框架在设计和编码层次究竟有哪些过人的地方?当然, ...
- swift3 0 Alamofire下载文件
//下载文件的保存路径( var destination:DownloadRequest.DownloadFileDestination! //用于停止下载时,保存已下载的部分 var cancell ...
- Alamofire 的使用
最近,AFNetworking 的作者Mattt Thompson提交了一个新的类似于 AFNetworking 的网络 基础库,并且是专门使用最新的 Swift 语言来编写的,名为:Alamofir ...
- Alamofire源码解读系列(五)之结果封装(Result)
本篇讲解Result的封装 前言 有时候,我们会根据现实中的事物来对程序中的某个业务关系进行抽象,这句话很难理解.在Alamofire中,使用Response来描述请求后的结果.我们都知道Alamof ...
- Alamofire的简单封装
因为接下来需要请求数据进行展示,由于使用的代码语言是swift,这里利用cocoapods引入Alamofire,同样是AFNetworking的作者针对swift写的开源库,专门用来处理网络请求.为 ...
最新文章
- PE学习(三)第三章:PE文件头
- 禁用Intel ME
- mysql 自带 数据库_mysql自带的4个数据库介绍
- Flink 广播变量
- python程序发布 ubuntu_在ubuntu16.04的虚拟环境中运行Python程序作为服务
- jq之mouseleave()
- [BZOJ5329][Sdoi2018]战略游戏 圆方树+虚树
- ROS限速不生效问题
- [分享]四杂.cn中未被注册的好组合
- selenium+python自动化106 - 滑动 iframe 上的滚动条
- 使用腾讯云部署war包
- 浅析信号与系统2(离散时间复指数序列的周期性质)
- ubuntu 18.04.6 内网PXE实战preseed案例
- linux互信文件,linux SSH互信
- toolbar遇到问题和解决方式
- 利用Retrofit, RxJava获取网络内容
- python中re.search()函数的用法
- logback使用配置详解
- java 1 2 等于_java 判断语句中一个等于号和两个等于号的区别是什么?
- Sony vegas 制作电子相册