Trong Swift 3 bạn có thể:
let url = URL(string: "http://www.thisismylink.com/postName.php")!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
let postString = "id=13&name=Jack"
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()
này kiểm tra cho cả lỗi mạng cơ bản cũng như các lỗi HTTP cấp cao.
Xem previous revision of this answer để hiển thị Swift 2.
FYI, nếu bạn muốn thực hiện các yêu cầu thực tế (bao gồm phần trăm thoát, tạo các yêu cầu phức tạp, đơn giản hóa việc phân tích phản hồi), hãy cân nhắc sử dụng [AlamoFire] (https://github.com/Alamofire/Alamofire), từ tác giả của AFNetworking. Nhưng nếu bạn chỉ muốn thực hiện một yêu cầu 'POST' nhỏ nhặt, bạn có thể sử dụng ở trên. – Rob
Cảm ơn Rob, Đó chỉ là những gì tôi đang tìm kiếm! Không có gì nhiều hơn một POST đơn giản. Câu trả lời chính xác! – angeant
Sau một vài giờ tìm kiếm một số giải pháp khác nhau, dòng 3 và 4 là tiết kiệm cuộc sống của tôi như tôi không thể cho cuộc sống của tôi nhận được NSJSONSerialization.dataWithJSONObject để làm việc! – Zork