将json参数发布到api使用post方法Swift 3

时间:2017-05-27 04:57:17

标签: javascript ios xcode swift3 http-post

我需要将以下json传递给此函数,以便Shopify Api可以理解提交。我无法创建正确的变量格式并将其传递给server.Shopify API期望通过POST传递以下json

1 个答案:

答案 0 :(得分:0)

将REQUEST_URL替换为您的API网址

将JSON_STRING替换为您的实际json字符串

var request = URLRequest(url: URL(string: "REQUEST_URL")!)
request.httpMethod = "POST"
let postString = "JSON_STRING" 
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard let data = data, error == nil else {                                                 // check for fundamental networking error
    print("error=\(error)")
    return
}

if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
    print("statusCode should be 200, but is \(httpStatus.statusCode)")
    print("response = \(response)")
}

let responseString = String(data: data, encoding: .utf8)
   print("responseString = \(responseString)")
}
task.resume()

将您的对象转换为字典,然后按

序列化
   do{
        let data = try JSONSerialization.data(withJSONObject: dict, options: [])
        postString = String.init(data: data, encoding: String.Encoding.utf8)!
    }catch{
        print(error)
    }