gpt4 book ai didi

ios - PushViewController 在 httpPost 之后不起作用

转载 作者:行者123 更新时间:2023-11-29 00:25:51 25 4
gpt4 key购买 nike

我制作了一个登录屏幕,它接受输入并与 REST api 通信以验证用户。如果响应为真,我将登录用户,否则不会。我写了一个方法 openViewControllerBasedOnIdentifier(id) 来切换 View 。

REST api 适本地返回 true 和 false。推送 Controller 被调用,但 View 没有改变。如果我在 LoginAction 方法 'self.openViewControllerBasedOnIdentifier("PlayVC")' 中只放置一行并删除其余代码,它会如何工作?

这是我的代码 @IBAction func LoginAction(_ sender: Any) {

    //self.openViewControllerBasedOnIdentifier("PlayVC")

Constants.login_status = false
//created NSURL
let requestURL = NSURL(string: URL_BK)

//creating NSMutableURLRequest
let request = NSMutableURLRequest(url: requestURL! as URL)

//setting the method to post
request.httpMethod = "POST"
let username = phonenumber.text

//creating the post parameter by concatenating the keys and values from text field
let postParameters = "username="+username!+"&password=bk&schoolId=0";

//adding the parameters to request body
request.httpBody = postParameters.data(using: String.Encoding.utf8)


//creating a task to send the post request
let task = URLSession.shared.dataTask(with: request as URLRequest){
data, response, error in
let responseData = String(data: data!, encoding: String.Encoding.utf8)
if error != nil{
print("error is \(error)")
return;
}

//parsing the response
do {

print(“Received data is ---%@",responseData as Any)

let myJSON = try JSONSerialization.jsonObject(with: data! , options: .allowFragments) as? NSDictionary


if let parseJSON = myJSON {


var status : Bool!

status = parseJSON["status"] as! Bool?
//print(status)

if status==false
{
Constants.login_status = false

}
else{
Constants.login_status = true
print("calling PLAYVC")

self.openViewControllerBasedOnIdentifier("PlayVC")


}

}
else{
print("NULL VALUE RECEIVED")
}


} catch {
print(error)
}

}
//executing the task
task.resume()




}

最佳答案

你应该像这样在主线程上打开新的 View Controller :

DispatchQueue.main.async {
self.openViewControllerBasedOnIdentifier("PlayVC")
}

当您调用 URLSession.shared.dataTask 时,您的 REST API 查询响应在后台线程中处理,因此当您调用任何 UI 操作时,您应该像上面那样包装代码以执行 UI 代码在主线程中。然后就可以正常工作了:)

关于ios - PushViewController 在 httpPost 之后不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43060012/

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