Alamofire:Swift的HTTP 网络库

安装

  • CocoaPods和Carthage都很方便安装
    安装完,如果出现加载不到Alamofire,可以查看Cannot load underlying module for 'Alamofire' #441,问题应该可以解决。
  • 手动安装
    • 下载Alamofire
    • Alamofire.xcodeproj拖进到项目中

    • "Embedded Binaries中添加

    • command + B 编译后就可以使用

关于 https://httpbin.org/ 网站

https://httpbin.org/ 网站可用来做http的各种请求测试使用,不过遗憾的是没有POST等提交类型请求的测试

基本使用

一个简单的请求:

import Alamofire

Alamofire.request("https://httpbin.org/get")

http中有请求(Request)响应(Response)两个重要概念。大部分http框架,都会使用requestresponse作为方法名。
看看Alamofire的request方法的详细参数:

  public func request(
      _ url: URLConvertible,
      method: HTTPMethod = .get,
      parameters: Parameters? = nil,
      encoding: ParameterEncoding = URLEncoding.default,
      headers: HTTPHeaders? = nil)
      -> DataRequest
  {

url,method,parameters,encoding,headers五个参数,与http是相互对应的。其中只有url是必须的,其它都有默认值。

请求后的响应处理

向http发送请求后,就需对响应结果进行处理。** Alamofire采用链式调用的方式处理响应,这种链式调用的方式最初应该是起源jQuery**。
响应处理的一般形式如下,response就是响应结果。

Alamofire.request("https://httpbin.org/get").responseJSON { response in

}

Alamofire 提供了五种不同的响应处理:

  // Response Handler - Unserialized Response
  func response(
      queue: DispatchQueue?,
      completionHandler: @escaping (DefaultDataResponse) -> Void)
      -> Self

  // Response Data Handler - Serialized into Data
  func responseData(
      queue: DispatchQueue?,
      completionHandler: @escaping (DataResponse<Data>) -> Void)
      -> Self

  // Response String Handler - Serialized into String
  func responseString(
      queue: DispatchQueue?,
      encoding: String.Encoding?,
      completionHandler: @escaping (DataResponse<String>) -> Void)
      -> Self

  // Response JSON Handler - Serialized into Any
  func responseJSON(
      queue: DispatchQueue?,
      completionHandler: @escaping (DataResponse<Any>) -> Void)
      -> Self

  // Response PropertyList (plist) Handler - Serialized into Any
  func responsePropertyList(
      queue: DispatchQueue?,
      completionHandler: @escaping (DataResponse<Any>) -> Void))
      -> Self

五种方法的参数不同,但最后一参数都是一个回调的闭包,都可以写成尾随闭包形式。除了response方法的回调参数是DefaultDataResponse,其它都是DataResponse:

   public struct DataResponse<Value> {
       /// The URL request sent to the server.
       public let request: URLRequest?

       /// The server's response to the URL request.
       public let response: HTTPURLResponse?

       /// The data returned by the server.
       public let data: Data?

       /// The result of response serialization.
       public let result: Result<Value>

       /// The timeline of the complete lifecycle of the request.
       public let timeline: Timeline

       /// Returns the associated value of the result if it is a success, `nil` otherwise.
       public var value: Value? { return result.value }

       /// Returns the associated error value if the result if it is a failure, `nil` otherwise.
       public var error: Error? { return result.error }

       var _metrics: AnyObject?

DataResponseDefaultDataResponse最大的不同就是多了两个属性resultvaluevalue值就是格式化的不同类型。

响应处理的一些例子

  • 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)")
            }
        }
    
    response方法的响应结果responseDefaultDataResponse,没有进行过格式化处理。
  • responseData
        Alamofire.request("https://httpbin.org/get").responseData { response in
            debugPrint("All Response Info: \(response)")
            
            if let data = response.result.value, let utf8Text = String(data: data, encoding: .utf8) {
                print("Data: \(utf8Text)")
            }
        }
    
    responseData方法对响应结果进行了处理,response.result.value就是我们属性的Data类型。
  • 链式调用
      Alamofire.request("https://httpbin.org/get")
      .responseString { response in
              print("Response String: \(response.result.value)")
      }
      .responseJSON { response in
          print("Response JSON: \(response.result.value)")
      }
    

响应验证

http响应结果中的不同状态码(100..<600)表示不同结果。

  • 手动验证
    Alamofire.request("https://httpbin.org/get")
     .validate(statusCode: 200..<300)
     .validate(contentType: ["application/json"])
     .responseData { response in
         switch response.result {
         case .success:
             print("Validation Successful")
         case .failure(let error):
             print(error)
         }
     }
    
  • 自动验证
    状态码在200..<300的为正确,其它为错误。
    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不同请求方式

request方法的method参数表示不同的方法。

Alamofire.request("https://httpbin.org/get") // method defaults to `.get`

Alamofire.request("https://httpbin.org/post", method: .post)
Alamofire.request("https://httpbin.org/put", method: .put)
Alamofire.request("https://httpbin.org/delete", method: .delete)

请求参数编码

GET的参数按照固定格式写到URL中,其他类型则按照不同格式写到请求body中。

  • GET参数编码

          let parameters: Parameters = ["foo": "bar"]
          
          // All three of these calls are equivalent
          Alamofire.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))
          
          // https://httpbin.org/get?foo=bar
    
  • POST参数编码

          let parameters: Parameters = [
              "foo": "bar",
              "baz": ["a", 1],
              "qux": [
                  "x": 1,
                  "y": 2,
                  "z": 3
              ]
          ]
          
          // All three of these calls are equivalent
          Alamofire.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)
          
          // HTTP body: foo=bar&baz[]=a&baz[]=1&qux[x]=1&qux[y]=2&qux[z]=3
    
  • JSON编码

          let parameters: Parameters = [
              "foo": [1,2,3],
              "bar": [
                  "baz": "qux"
              ]
          ]
          
          // Both calls are equivalent
          Alamofire.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: []))
          
          // HTTP body: {"foo": [1, 2, 3], "bar": {"baz": "qux"}}
    

添加请求HTTP头部

let headers: HTTPHeaders = [
  "Authorization": "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==",
  "Accept": "application/json"
]

Alamofire.request("https://httpbin.org/headers", headers: headers).responseJSON { response in
  debugPrint(response)
}

HTTP认证

      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)
      }

下载文件

        Alamofire.download("https://httpbin.org/image/png").responseData { 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.appendingPathComponent("pig.png")
            
            return (fileURL, [.removePreviousFile, .createIntermediateDirectories])
        }
        
        Alamofire.download("https://httpbin.org/image/png", to: destination).response { response in
            print(response)
            
            if response.error == nil, let imagePath = response.destinationURL?.path {
                let image = UIImage(contentsOfFile: imagePath)
                self.imageView.image = image
                self.tableView.reloadData()
            }
        }

上传

  • 上传 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").responseJSON { response in
              debugPrint(response)
          }
    
  • 上传Multipart Form Data(表单提交)
          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)
                  }
          }
          )
    

请求中花费的各种时间

Alamofire.request("https://httpbin.org/get").responseJSON { response in
    print(response.timeline)
}

结果:

Timeline: { "Latency": 1.527 secs, "Request Duration": 1.528 secs, "Serialization Duration": 0.001 secs, "Total Duration": 1.529 secs }
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,736评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,167评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,442评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,902评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,302评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,573评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,847评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,562评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,260评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,531评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,021评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,367评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,016评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,068评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,827评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,610评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,514评论 2 269

推荐阅读更多精彩内容