如何在Swift中使用JSON POST方法将字典值传递给键中的参数

问题描述 投票:0回答:1

对于下面的API,必须传递标头和参数。

工作网址:http://itaag-env-1.ap-south-1.elasticbeanstalk.com/editprofile/

其标题:[“设备ID”:“ 584D97F-761A-4C24-8C4B-C145A8B8BD75”,“ userType”:“个人”,“密钥”:“ 9609cc826b0d472faf9967370c095c21”]

其参数:

profileImage和ContentType.MULTIPART_FORM_DATA:“多部分/表单数据”

profiledetails:“ {” firstName“:” Satish“,” lastName“:” Madhavarapu“,” gender“:” male“,” ageGroup“:” 40-50“}”]

像这样在POSTMAN中,我们得到输出:

POSTMAN image with parameters and response

这里是代码,这里如何添加profiledetails参数:

func getPostString(params:[String:Any]) -> String
{
    var data = [String]()
    for(key, value) in params
    {
        data.append(key + "=\(value)")
    }
    print(data.map { String($0) }.joined(separator: "&"))
    return data.map { String($0) }.joined(separator: "&")
}

func callPostApi(){
    let url = URL(string: "http://itaag-env-1.ap-south-1.elasticbeanstalk.com/editprofile/")
    guard let requestUrl = url else { fatalError() }
    var request = URLRequest(url: requestUrl)
    request.httpMethod = "POST"

    request.setValue("584D97F-761A-4C24-8C4B-C145A8B8BD75", forHTTPHeaderField: "deviceid")
    request.setValue("9609cc826b0d472faf9967370c095c21", forHTTPHeaderField: "key")
    request.setValue("personal", forHTTPHeaderField: "userType")

    let parameters = getPostString(params:   ["profileImage and ContentType.MULTIPART_FORM_DATA": "multipart/form-data", "profiledetails": "{"firstName":"Satish", "lastName":"Madhavarapu","gender":"male", "ageGroup":"40-50"}"])
    request.httpBody = parameters.data(using: .utf8)
    // Perform HTTP Request
    let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
            let httpResponse = response as? HTTPURLResponse
            print(httpResponse!.statusCode)
            // Check for Error
            if let error = error {
                print("Error took place \(error)")
                return
            }

            // Convert HTTP Response Data to a String
            if let data = data, let dataString = String(data: data, encoding: .utf8) {
                print("Response data string:\n \(dataString)")
            }
    }
    task.resume()
}

如何添加参数:

let parameters = getPostString(params:   ["profileImage and ContentType.MULTIPART_FORM_DATA": "multipart/form-data", "profiledetails": "{"firstName":"Satish", "lastName":"Madhavarapu","gender":"male", "ageGroup":"40-50"}"])

如何添加参数字典值,请帮助我代码。

ios json swift post parameters
1个回答
0
投票

您需要使用字典数组,以便更改方法的定义

© www.soinside.com 2019 - 2024. All rights reserved.