[英]PushViewController doesn't work after httpPost
我制作了一個登錄屏幕,該屏幕接受輸入並與REST API通信以驗證用戶。 如果響應為真,則我不登錄用戶。 我寫了一個方法openViewControllerBasedOnIdentifier(id)來切換視圖。
REST API會正確返回true和false。 推送控制器被調用,但視圖不變。 如果我僅在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()
}
您應該像這樣在主線程上打開新的視圖控制器:
DispatchQueue.main.async {
self.openViewControllerBasedOnIdentifier("PlayVC")
}
當您調用URLSession.shared.dataTask
時,您的REST API查詢響應將在后台線程中處理,因此,當您調用任何UI動作時,都應按上述方式包裝代碼以在主線程中執行UI代碼。 然后就可以了:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.