我创建了一个登录屏幕,它接受输入并与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()
}
答案 0 :(得分:1)
您应该在主线程上打开新的视图控制器,如下所示:
DispatchQueue.main.async {
self.openViewControllerBasedOnIdentifier("PlayVC")
}
当您调用URLSession.shared.dataTask
时,在后台线程中处理您的REST API查询响应,因此当您调用任何UI操作时,您应该如上所述包装代码以在主线程中执行UI代码。然后它会工作正常:))