swift Alamofire 用法介绍

  • 1.基本用法
Alamofire.request("https://httpbin.org/get").responseJSON { (response) in
    
            // original url request
            print("Request: \(String(describing: response.request))")
            // http url response
            print("Response: \(String(describing: response.response))")
            // response serialization result
            print("Result: \(response.result)")
            
            if let json = response.result.value {
                print("JSON:\(json)") // serialized json response
            }
            
            if let data = response.data, let utf8Text = String(data: data, encoding: .utf8) {
                print("Data: \(utf8Text)") // original server data as UTF8 string
            }
        }
  • 2.链式响应
Alamofire.request("https://httpbin.org/get").responseString { (response) in
            print("Response String: \(String(describing: response.result.value))")
            }.responseJSON { (response) in
                print("Response JSON:\(String(describing: response.result.value)")
        }
  • 添加Headers和parameter
let parameters: Parameters = [
            "foo": "bar",
            "baz": ["a", 1],
            "qux": [
                "x": 1,
                "y": 2,
                "z": 3
            ]
        ]
        let headers: HTTPHeaders = [
            "Accept" : "application/json",
            "Authorization" : "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=="
        ]
        Alamofire.request("https://httpbin.org/post", method: .post, parameters: parameters, encoding: URLEncoding.httpBody, headers: headers)
  • 自定义队列
    /**
     默认情况下,响应处理是在主线程执行,也可以自定义
     */
let utilityQueue = DispatchQueue.global(qos: .utility)   
      Alamofire.request("https://httpbin.org/get").responseJSON(queue: utilityQueue, options: []) { (response) in
            print("Executing response handler on utility queue")
        }
  • Response Validation
Alamofire.request("https://httpbin.org/get")
        .validate(statusCode: 200..<300)
        .validate(contentType: ["application/json"])
            .responseData { (response) in
                switch response.result {
                case .success:
                    print("successful")
                case .failure:
                    print("error")
                }
  • 下载文件
 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)
                }
        }
  • 上传Data数据
let imageData = UIImagePNGRepresentation(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")
            .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)
        }
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,860评论 18 139
  • Alamofire 是一款 Swift 写的 HTTP 网络请求库 前言 本篇内容为 Alamofire 官方 R...
    zongmumask阅读 20,933评论 6 66
  • 尽管Alamofire的github文档已经做了很详细的说明,我还是想重新梳理一遍它的各种用法,以及这些方法的一些...
    老马的春天阅读 16,154评论 28 135
  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    阳明AGI阅读 16,003评论 3 119
  • 听很多人说起过简书,今天终于下了一个,用微信登陆注册了一个,系统在微信昵称后面加了后缀算是我在简书的昵称,想用...
    禾颜越瑟阅读 184评论 0 3