POST request with data in body with Alamofire 4

旧城冷巷雨未停 提交于 2019-11-26 20:37:12

问题


how is it possible to send a POST request with a data in the HTTP body with Alamofire 4? I used custom encoding at swift 2.3 it was working good. I converted my code swift 3 and I tried to paramater encoding but not working. This code :

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
}

and Alamofire request :

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

回答1:


You need to send request like below in 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)
                }
}



回答2:


This will work better in 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)
}



回答3:


Alamofire using post method import UIKit import Alamofire

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



回答4:


Alamofire for GET and POST method using Alamofire

1.Create a file named "GlobalMethod" for multiple use

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. In the View Controller call "ServiceMethod" created in GlobalMethod by sending values to call API Service

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


来源:https://stackoverflow.com/questions/40604502/post-request-with-data-in-body-with-alamofire-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!