ios 带有 Alamofire 4 正文数据的 POST 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40604502/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 10:48:13  来源:igfitidea点击:

POST request with data in body with Alamofire 4

iosswiftencodingswift3alamofire

提问by Cagatay

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 :

如何使用 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
}

and Alamofire request :

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

回答by Ekta Padaliya

You need to send request like below in swift 3

您需要在 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 with Alamofire 5:

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

回答by Raghib Arshi

This will work better in Swift 4.

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

回答by CSE 1994

Alamofire using post method import UIKit import Alamofire

Alamofire 使用 post 方法 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)
            }
        }
}

回答by Sandeep Kalia

Alamofire for GET and POST method using Alamofire

使用 Alamofire 实现 GET 和 POST 方法的 Alamofire

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

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. 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)
                }
            }
    
  1. 在 View Controller 中,通过发送值调用 API 服务来调用 GlobalMethod 中创建的“ServiceMethod”

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