Alamofire-使用

所有类型请求,Alamofire都直接提供,通过Alamofire直接调用,配置相关参数即可。示例如下:

1、GET请求

let urlStr = "http://onapp.yahibo.top/public/?s=api/test/list"
Alamofire.request(url).responseJSON { (response) in
    switch response.result {
    case .success(let json):
        print(json)
        break
    case .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) in
    switch response.result {
    case .success(let json):
        print(json)
        break
    case .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) in
    let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
    let time = Date().timeIntervalSince1970
    let fileURL = documentsURL.appendingPathComponent("\(time).mp4")
    print("沙盒路径:\(documentsURL)")
    return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
}).downloadProgress { (progress) in
    print(progress)
}
  • 获取沙盒路径转存视频文件

4、上传表单

let imgArr:Array = [UIImage.init(named: "headimg"),UIImage.init(named: "headimg")]
Alamofire.upload(multipartFormData: { (formData) in
    formData.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) in
    switch result {
    case .success(let upload, _, _):
        upload.uploadProgress(closure: { (progress) in
            print(progress)
        }).responseJSON(completionHandler: { (response) in
            switch response.result {
            case .success(let json):
                print(json)
                break
            case .failure(let error):
                print("error:\(error)")
                break
            }
        })
        break
    case .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.defaultHTTPHeaders
        return SessionManager(configuration: configuration)
    }()
}

调用发起下载请求:

BackgroundManager.shared.manager.download(url) { (url, response) -> (destinationURL: URL, options: DownloadRequest.DownloadOptions) in
                let 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) in
                print(progress)
            }.response(queue: DispatchQueue.global(qos: .utility), completionHandler: { (response) in
                print("完成下载:\(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 = urlRequest
        request.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) in
    switch response.result {
    case .success(let json):
        print(json)
        break
    case .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) in
    switch response.result {
    case .success(let json):
        print(json)
        break
    case .failure(let error):
        print("error:\(error)")
        break
    }
}

该重定向不常用,如应用被逆向,给个重定向,就是不给你数据。

8、重新请求

同上面协议,创建子类实现方法,调用即可。

实现协议方法

class MyRetrier: RequestRetrier{
    var count: Int = 0
    func 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 in
    print(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-使用)