衆所周知,異步發佈請求更好,因爲用戶不會在加載漫長過程時感覺應用「崩潰」。如何將同步發佈請求轉換爲異步發佈請求?
但是,我不確定從哪裏開始將同步發佈請求轉換爲Swift代碼的異步發佈請求。
我現在這樣的代碼:
所有的func checkLogin() {
let username:NSString = txtUsername.text! as NSString
let password:NSString = txtPassword.text! as NSString
do {
let post:NSString = "username=\(username)&password=\(password)" as NSString
NSLog("PostData: %@",post);
let url:URL = URL(string:"https://example.com/login.php")!
let postData:Data = post.data(using: String.Encoding.ascii.rawValue)!
let postLength:NSString = String(postData.count) as NSString
let request:NSMutableURLRequest = NSMutableURLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = postData
request.setValue(postLength as String, forHTTPHeaderField: "Content-Length")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField: "Accept")
var reponseError: NSError?
var response: URLResponse?
var urlData: Data?
do {
urlData = try NSURLConnection.sendSynchronousRequest(request as URLRequest, returning:&response)
} catch let error as NSError {
reponseError = error
urlData = nil
}
if (urlData != nil) {
let res = response as! HTTPURLResponse!;
NSLog("Response code: %ld", res?.statusCode);
if ((res?.statusCode)! >= 200 && (res?.statusCode)! < 300) {
let responseData:NSString = NSString(data:urlData!, encoding:String.Encoding.utf8.rawValue)!
NSLog("Response ==> %@", responseData);
let jsonData:NSDictionary = try JSONSerialization.jsonObject(with: urlData!, options:JSONSerialization.ReadingOptions.mutableContainers) as! NSDictionary
let success:NSInteger = jsonData.value(forKey: "success") as! NSInteger
NSLog("Success: %ld", success);
if(success == 1)
{
// do something, code removed
} else {
var error_msg:NSString
if jsonData["error_message"] as? NSString != nil {
error_msg = jsonData["error_message"] as! NSString
} else {
error_msg = "Unknown Error"
}
// show alert
}
}
}
}
}
謝謝您的回答!我不確定如何提交我的帖子值,以及如何解析收到的JSON? – Panda
@Panda你的請求也會一樣,你也完成了JSON解析。爲了在Swift 3中使用,您可能需要做的改變可能很少。您可以輕鬆地做到這一點。首先深入這一點。快樂編碼..! –