繁体   English   中英

在httpPost之后,PushViewController不起作用

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM