私はチャットアプリを構築していますが、データを受け取る方法を理解していますが、データの送信に問題があります。私は、ユーザー名とメッセージである2つのUITextField値を取得し、データを送信しようとしています。スウィフトでJSONデータを送信
@IBAction func sendMessage(_ sender: UIButton) {
let parameters = ["user": username.text, "message": textBox.text] as! [String: String]
//create the url with NSURL
let url = NSURL(string: "http://website.com/getChatLogJSON.php")
//create the session object
let session = URLSession.shared
//now create the NSMutableRequest object using the url object
let request = NSMutableURLRequest(url: url! as URL)
request.httpMethod = "POST" //set http method as POST
do {
request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
} catch let error {
print(error.localizedDescription)
}
//HTTP Headers
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
//create dataTask using the session object to send data to the server
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
guard error == nil else {
return
}
guard let data = data else {
return
}
do {
//create json object from data
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: AnyObject] {
print(json)
// handle json...
}
} catch let error {
print(error.localizedDescription)
}
})
task.resume()
}
どうしてうまくいかないのですか?どのようなエラーが出ますか?ところで、なぜ '.prettyPrinted'ですか?サーバーは気にしません。そしてなぜ '.mutableContainers'なのでしょうか?スウィフトでは意味がありません。どちらの場合も、 'options'パラメータを削除してください。そしてSwift 3+では 'URL'と' URLRequest'、そしてJSON辞書は '[String:Any]' – vadian
です。データを送信する際に何が問題になりますか? –