gpt4 book ai didi

ios - 如何将同步发布请求转换为异步发布请求?

转载 作者:可可西里 更新时间:2023-11-01 00:42:11 25 4
gpt4 key购买 nike

众所周知,异步发布请求更好,因为用户不会感觉到应用在加载漫长的过程时“崩溃”了。

但是,我不确定从哪里开始将同步发布请求转换为 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
}

}
}
}
}

最佳答案

首先不要使用 NSURLConnection,因为它现在已弃用。而是使用 NSURLSession

你可以像这样简单地使用:

let task = URLSession.shared().dataTask(with: request) {
data, response, error in
if (data) {

} else {
print("error=\(error!.localizedDescription)")
}
}
task.resume()

关于ios - 如何将同步发布请求转换为异步发布请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42391293/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com