Alamofire4.7 简单使用:

简单的GET/POST请求

GET请求:

Alamofire4,版本默认情况为get请求

let request:DataRequest = Alamofire.request("https://httpbin.org/get")
request.responseString { (responseString) in
    //...
    if let response = responseString.response {
      for (field, value) in response.allHeaderFields {
          print("\(field)===========\(value)")
      }
    }
}

使用.responseString 请求如果成功,返回resp.result.value就是String类型。 类似的,还有responseDataresponseJSON

POST请求:

.request(...) 方法中的很多参数是有缺省值的,因此可以根据实际情况决定添加哪些参数。

//可以不带参
var request:DataRequest = Alamofire.request("https://httpbin.org/post", method: .post)
//带参数
request = Alamofire.request("https://httpbin.org/post", method: .post, parameters: ["foo": "bar"])
//添加headers
request = Alamofire.request("https://httpbin.org/post", method: .post, parameters: ["foo": "bar"], encoding: JSONEncoding.default, headers: ["cc":"cc2"])

request
  ..validate() //会验证statusCode 200-299
  .authenticate(user: "", password: "") //URLCredential 相关
  .responseString { (reponse) in
      
      print(reponse)

      switch reponse.result {
          
      case .success(let x):
          
          print(x)
          
      case .failure(let error):
          
          print(error)
          self.errorHanding(error)
          
      }
}

Alamofire.SessionManager

可以对网络请求进行管理

配置超时时间

//设置延迟
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 4 // seconds
configuration.timeoutIntervalForResource = 4
   
let smg = Alamofire.SessionManager(configuration: configuration)
smg.request("http://10.10.60.78:8080", method: .get)
  .responseString { (reponse) in
      
}

取消网络请求

//取消网络请求
smg.session.getAllTasks { (tasks:[URLSessionTask]) in
  tasks.forEach({ (task) in
      
      if task.currentRequest?.url?.lastPathComponent == ""{
          task.cancel()
      }
  })
}

Error Handing

https://gist.github.com/tyrad/eeed687155ee1ad806fbe8757335a2b1

 func errorHanding(_ error:Error) {
        
        if let error = error as? AFError {
            switch error {
            case .invalidURL(let url):
                print("Invalid URL: \(url) - \(error.localizedDescription)")
            case .parameterEncodingFailed(let reason):
                print("Parameter encoding failed: \(error.localizedDescription)")
                print("Failure Reason: \(reason)")
            case .multipartEncodingFailed(let reason):
                print("Multipart encoding failed: \(error.localizedDescription)")
                print("Failure Reason: \(reason)")
            case .responseValidationFailed(let reason):
                print("Response validation failed: \(error.localizedDescription)")
                print("Failure Reason: \(reason)")
                
                switch reason {
                case .dataFileNil, .dataFileReadFailed:
                    print("Downloaded file could not be read")
                case .missingContentType(let acceptableContentTypes):
                    print("Content Type Missing: \(acceptableContentTypes)")
                case .unacceptableContentType(let acceptableContentTypes, let responseContentType):
                    print("Response content type: \(responseContentType) was unacceptable: \(acceptableContentTypes)")
                case .unacceptableStatusCode(let code):
                    print("Response status code was unacceptable: \(code)")
                }
            case .responseSerializationFailed(let reason):
                print("Response serialization failed: \(error.localizedDescription)")
                print("Failure Reason: \(reason)")
            }
            print("Underlying error: \(String(describing: error.underlyingError))")
        } else if let error = error as? URLError {
            print("URLError occurred: \(error)")
        } else {
            print("Unknown error: \(error)")
        }
    }