如何在Swift的Json POST方法中添加两个不同的参数

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

您好,下面的API我需要传递标题和参数

APIhttp://itaag-env-1.ap-south-1.elasticbeanstalk.com/editprofile/

标题["deviceid": "EC3746E9-4DB4-42C7-9D8C-1542B18C2AC9", "userType": "personal", "key": "5fe42fb3b54543a0bab5667cf96526f8"]

参数:

profileImage and ContentType.MULTIPART_FORM_DATA: multipart/form-data profiledetails: {"firstName":"Satish", "lastName":"Madhavarapu","gender":"male", "ageGroup":"40-50"}

POSTMAN Json Response

我尝试过在下面的代码中在哪里以及如何添加两个参数:

func editProfilr() {

let headers = ["deviceid": "EC3746E9-4DB4-42C7-9D8C-1542B18C2AC9","userType": "personal","key": "5fe42fb3b54543a0bab5667cf96526f8"]
let parameters: [String: Any] = ["firstName":"Satish", "lastName":"Madhavarapu","gender":"male", "ageGroup":"40-50"]

let URL_HEROES = "http://itaag-env-1.ap-south-1.elasticbeanstalk.com/editprofile/"
let url = URL (string: URL_HEROES)
var _ : NSError?
let jsonData = try! JSONSerialization.data(withJSONObject: parameters, options: JSONSerialization.WritingOptions.prettyPrinted)
let jsonString = NSString(data: jsonData, encoding: String.Encoding.utf8.rawValue)! as String
print(jsonString)
var request = URLRequest(url: url!)
request.httpMethod = "POST"
let postData = String(format: "profiledetails=%@",jsonString) .data(using: .utf8)
request.httpBody = postData
request.allHTTPHeaderFields = headers
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
    if (error != nil) {
        print(error!)
    } else {
        let httpResponse = response as? HTTPURLResponse
        print(httpResponse! as Any)

        if let jsonObj = try? JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? String{
            print("jsonobject \(jsonObj)")
        }
    }
})
dataTask.resume()

json}

以上,我试图添加profiledetails参数,如

 let postData = String(format: "profiledetails=%@",jsonString) .data(using: .utf8)

但是如何添加profileImage和ContentType.MULTIPART_FORM_DATA:multipart / form-data此参数。

请帮助我提供代码。

json swift post parameters
1个回答
0
投票

我已在线上为您找到,请查看:

func uploadImage(paramName: String, fileName: String, image: UIImage) {
    let url = URL(string: "http://api-host-name/v1/api/uploadfile/single")

    // generate boundary string using a unique per-app string
    let boundary = UUID().uuidString

    let session = URLSession.shared

    // Set the URLRequest to POST and to the specified URL
    var urlRequest = URLRequest(url: url!)
    urlRequest.httpMethod = "POST"

    // Set Content-Type Header to multipart/form-data, this is equivalent to submitting form data with file upload in a web browser
    // And the boundary is also set here
    urlRequest.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")

    var data = Data()

    // Add the image data to the raw http request data
    data.append("\r\n--\(boundary)\r\n".data(using: .utf8)!)
    data.append("Content-Disposition: form-data; name=\"\(paramName)\"; filename=\"\(fileName)\"\r\n".data(using: .utf8)!)
    data.append("Content-Type: image/png\r\n\r\n".data(using: .utf8)!)
    data.append(image.pngData()!)

    data.append("\r\n--\(boundary)--\r\n".data(using: .utf8)!)

    // Send a POST request to the URL, with the data we created earlier
    session.uploadTask(with: urlRequest, from: data, completionHandler: { responseData, response, error in
        if error == nil {
            let jsonData = try? JSONSerialization.jsonObject(with: responseData!, options: .allowFragments)
            if let json = jsonData as? [String: Any] {
                print(json)
            }
        }
    }).resume()
}
© www.soinside.com 2019 - 2024. All rights reserved.