gpt4 book ai didi

iOS - Swift : fetching data from database in main thread, 不在后台

转载 作者:行者123 更新时间:2023-11-28 13:26:41 24 4
gpt4 key购买 nike

在我的 iOS 应用程序中,我能够从数据库下载数据,但实际上所有操作都是在后台进行的,主线程仍然处于事件状态,甚至是 GUI。我也试着用

来“ sleep ”
DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(3)) { ... }

有了这个延迟,一切正常,但这不是一个好的解决方案。我如何更改我的代码以在主线程中执行此操作?可能与 loadingIndicator 一起使用。

这是我的代码(检查用户名是否存在):

func CheckIfUsernameExists(username : String, passwordFromDb : inout String, errorMsg : inout String)
{
//declare parameter as a dictionary which contains string as key and value combination. considering inputs are valid
var _errorMsg = ""
var _psw = ""
var parameters : [String : Any]?
parameters = ["username": username,
"action": "login"]

print(parameters!)

let session = URLSession.shared
let url = "http://www.thetestiosapp.com/LoginFunctions.php"
let request = NSMutableURLRequest()
request.url = URL(string: url)!
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.setValue("application/json", forHTTPHeaderField:"Accept")
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField:"Content-Type")

do{
request.httpBody = try JSONSerialization.data(withJSONObject: parameters!, options: .sortedKeys)
let task = session.dataTask(with: request as URLRequest, completionHandler: {(data, response, error) in
if let response = response {
let nsHTTPResponse = response as! HTTPURLResponse
let statusCode = nsHTTPResponse.statusCode
print ("status code = \(statusCode)")
}
if let error = error {
print ("\(error)")

}
if let data = data {
do{
_psw = self.parseJSON_CheckIfUsernameExists(data, errorMsg: &_errorMsg)
}
}
})
task.resume()
}catch _ {
print ("Oops something happened buddy")
errorMsg = "Usarname non recuperato (1)"
}

passwordFromDb = _psw
errorMsg = _errorMsg
}

最佳答案

您正试图在此方法的末尾更新 passwordFromDberrorMsg。但这是一个异步方法,并且那些局部变量 _psw_errorMsg 是在闭包内设置的。与其尝试将这些变量的检查推迟到 future 任意三秒钟,不如将您需要的任何“后请求”处理移动到该闭包中。例如

func CheckIfUsernameExists(username : String, passwordFromDb : inout String, errorMsg : inout String) {
//declare parameter as a dictionary which contains string as key and value combination. considering inputs are valid

let parameters = ...

let session = URLSession.shared
var request = URLRequest()
...

do {
request.httpBody = ...
let task = session.dataTask(with: request) { data, response, error in
if let httpResponse = response as? HTTPURLResponse,
let statusCode = httpResponse.statusCode {
print ("status code = \(statusCode)")
}

guard let data = data else {
print (error ?? "Unknown error")
return
}

let password = self.parseJSON_CheckIfUsernameExists(data, errorMsg: &_errorMsg)
DispatchQueue.main.async {
// USE YOUR PASSWORD AND ERROR MESSAGE HERE, E.G.:
self.passwordFromDb = password
self.errorMsg = _errorMsg
// INITIATE WHATEVER UI UPDATE YOU WANT HERE
}
}
task.resume()
} catch _ {
print ("Oops something happened buddy")
errorMsg = "Usarname non recuperato (1)"
}
}

关于iOS - Swift : fetching data from database in main thread, 不在后台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58249036/

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