Swift で JSON 本文を含む HTTP Post リクエストを作成するにはどうすればよいでしょうか? 質問する

Swift で JSON 本文を含む HTTP Post リクエストを作成するにはどうすればよいでしょうか? 質問する

JSON 本文を含む HTTP POST リクエストを作成しようとしています:

HTTP リクエスト本文に NSdictionnary を追加する方法。

これが私のコードですが、正しく動作していないようです。

var entry1 = Response(IdQuestion: 6510,IdProposition: 10,Time: 30)
var entry2 = Response(IdQuestion: 8284,IdProposition: 10,Time: 30)
Responses.append(entry1)
Responses.append(entry2)

let list = Responses.map { $0.asDictionary }

let json = ["List":list,"IdSurvey":"102","IdUser":"iOSclient","UserInformation":"iOSClient"]

let data: NSData = NSKeyedArchiver.archivedDataWithRootObject(json)

NSJSONSerialization.isValidJSONObject(json)

let myURL = NSURL(string: "http://www.myserver.com")!
let request = NSMutableURLRequest(URL: myURL)
request.HTTPMethod = "POST"

request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")

request.HTTPBody = data
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
    data, response, error in
    println(response)
    // Your completion handler code here
}
task.resume()

ベストアンサー1

これを試して、

// prepare json data
let json: [String: Any] = ["title": "ABC",
                           "dict": ["1":"First", "2":"Second"]]

let jsonData = try? JSONSerialization.data(withJSONObject: json)

// create post request
let url = URL(string: "http://httpbin.org/post")!
var request = URLRequest(url: url)
request.httpMethod = "POST"

// insert json data to the request
request.httpBody = jsonData

let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data, error == nil else {
        print(error?.localizedDescription ?? "No data")
        return
    }
    let responseJSON = try? JSONSerialization.jsonObject(with: data, options: [])
    if let responseJSON = responseJSON as? [String: Any] {
        print(responseJSON)
    }
}

task.resume()

または便利な方法を試すアラモファイア

おすすめ記事