【问题标题】:POST request with data in body with Alamofire 4使用 Alamofire 4 在正文中包含数据的 POST 请求
【发布时间】:2017-03-29 00:29:28
【问题描述】:

如何使用 Alamofire 4 发送带有 HTTP 正文中数据的 POST 请求?我在 swift 2.3 中使用了自定义编码,效果很好。我将我的代码转换为 swift 3 并尝试参数化编码但不工作。这段代码:

public struct MyCustomEncoding : ParameterEncoding {
private let data: Data
init(data: Data) {
    self.data = data
}
public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest {

    var urlRequest = try urlRequest.asURLRequest()        
    do {            
            urlRequest.httpBody = data
            urlRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")

    } catch {
        throw AFError.parameterEncodingFailed(reason: .jsonEncodingFailed(error: error))
    }

    return urlRequest
}

和 Alamofire 请求:

let enco : ParameterEncoding = MyCustomEncoding(data: ajsonData)
    Alamofire.request(urlString, method: .post , parameters: [:], encoding: enco , headers: headers).validate()
                .responseJSON { response in
                    switch response.result {
                    case .success:
                        print(response)

                        break
                    case .failure(let error):

                        print(error)
                    }
    }

【问题讨论】:

    标签: ios swift encoding swift3 alamofire


    【解决方案1】:

    您需要在 swift 3 中发送如下请求

    let urlString = "https://httpbin.org/get"
    
    Alamofire.request(urlString, method: .post, parameters: ["foo": "bar"],encoding: JSONEncoding.default, headers: nil).responseJSON {  
    response in
      switch response.result {
                    case .success:
                        print(response)
    
                        break
                    case .failure(let error):
    
                        print(error)
                    }
    }
    

    Swift 5 与 Alamofire 5:

    AF.request(URL.init(string: url)!, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { (response) in
            print(response.result)
    
            switch response.result {
    
            case .success(_):
                if let json = response.value
                {
                    successHandler((json as! [String:AnyObject]))
                }
                break
            case .failure(let error):
                failureHandler([error as Error])
                break
            }
        }
    

    【讨论】:

    • 我无法在 PHP 中访问这个 post 数组,在 PHP 中 post 数组是空的。请告诉我如何在 PHP 中使用 post 参数
    • 如果我只有“查询”键并且值可能总是不同,你能说一下我应该如何形成我的身体参数吗?我需要为搜索请求添加“查询”参数
    【解决方案2】:

    Alamofire 使用 post 方法 导入 UIKit 进口阿拉莫火

    class ViewController: UIViewController {
        let parameters = [
            "username": "foo",
            "password": "123456"
        ]
        let url = "https://httpbin.org/post"
    
    override func viewDidLoad() {
            super.viewDidLoad()
    Alamofire.request(url, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: [:]).responseJSON {
                response in
                switch (response.result) {
                case .success:
                    print(response)
                    break
                case .failure:
                    print(Error.self)
                }
            }
    }
    

    【讨论】:

      【解决方案3】:

      这在 Swift 4 中会更好。

      let url = "yourlink.php". // This will be your link
      let parameters: Parameters = ["User_type": type, "User_name": name, "User_email": email, "User_contact": contact, "User_password": password, "from_referral": referral]      //This will be your parameter
      
      Alamofire.request(url, method: .post, parameters: parameters).responseJSON { response in
          print(response)
      }
      

      【讨论】:

        【解决方案4】:

        请在下面找到代码

        **

        pod 'Alamofire', '~> 5.4'

        ** **

        pod 'ObjectMapper', '~> 4.2'

        ** **

        pod 'SwiftyJSON'

        **

        pod 'TPKeyboardAvoiding'

        使用模型

        import ObjectMapper
                
        class LoginModel : Mappable{
                
                var status : String?
                var data : [DataModel]?
                var message : String?
            
                required init?(map: Map) {
                }
            
                func mapping(map: Map) {
                    status <- map["status"]
                    data <- map["data"]
                    message <- map["message"]
                }
            }
            
            class DataModel : Mappable{
                var access_token : String?
                var isvideo : String?
                
                required init?(map: Map) {
                    
                }
                
                func mapping(map: Map) {
                    access_token <- map["access_token"]
                    isvideo <- map["isvideo"]
                }
            }
        

        调用 API

        HTTPNetwork().getHTTPData("", parameters: LoginParameter, completion: {(successresponse) -> Void in
                        
                        if let res = successresponse{
                            print("sucess token \(res["message"].string!)")
                            if let myuser = Mapper<DataModel>().map(JSONString: res["data"].rawString()!){
                                print("access_token \(myuser.access_token)")
                            }
                        }
                    }, error: {(errorresponse)-> Void in
                        if let res = errorresponse{
                            print("Error response token \(res)")
                        }
                    })
        
        
        public func getHTTPData(_ request: String, parameters : Parameters?, completion: @escaping (  JSON?) -> Void, error: @escaping ( JSON?) -> Void){
            AF.request(URL.init(string: "url")!, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: ["Content-Type":"application/json"]).responseJSON { (response) in
                print(response.result)
                
                switch response.result{
                case .success:
                    if let json = response.value as? [String : Any]{
                        if let output:JSON = JSON(response.value!){
                            if json["isSuccess"] as? Int == 1{
                                completion(output)
                            }else{
                                error(output)
                            }
                        }
                    }else{
                        completion(nil)
                    }
                case .failure:
                    completion(nil)
                }
            }
        }
        

        【讨论】:

          【解决方案5】:

          使用 Alamofire 的 GET 和 POST 方法的 Alamofire

          1.创建一个名为“GlobalMethod”的文件以供多次使用

          import Alamofire
          class GlobalMethod: NSObject {
          
              static let objGlobalMethod = GlobalMethod()
          
              func ServiceMethod(url:String, method:String, controller:UIViewController, parameters:Parameters, completion: @escaping (_ result: DataResponse<Any>) -> Void) {
          
                      var headers = Alamofire.SessionManager.defaultHTTPHeaders
                      headers["HeaderKey"] = "HeaderKey"
                      if method == "POST" {
                          methodType = .post
                          param = parameters
                      }
                      else {
                          methodType = .get
                      }
                      Alamofire.request(url, method: methodType, parameters: param, encoding: JSONEncoding.default, headers:headers
                          ).responseJSON
                          { response in
          
                              completion(response)
                      }
                  }
          }
          
          1. 在 View Controller 中调用“ServiceMethod”,通过发送值调用在 GlobalMethod 中创建的 API 服务

            let urlPath = "URL STRING"
            let methodType = "GET" or "POST" //as you want
            let params:[String:String] = ["Key":"Value"]
            
            GlobalMethod.objGlobalMethod.ServiceMethod(url:urlPath, method:methodType, controller:self, parameters:params)
                    {
                        response in
            
                        if response.result.value == nil {
                            print("No response")
                            return
                        }
                        else {
                          let responseData = response.result.value as! NSDictionary
                          print(responseData)
                        }
                    }
            

          【讨论】:

            猜你喜欢
            • 2017-12-03
            • 2019-05-23
            • 2015-10-28
            • 2019-03-24
            • 1970-01-01
            • 2020-12-23
            • 2018-05-07
            • 2015-03-07
            相关资源
            最近更新 更多