Call performSegue after URLSession.shared.dataTask

一世执手 提交于 2019-12-24 05:46:07

问题


I want to performe a Segue after sending a post request using URLSession.shared.dataTask

ViewController:

    @IBAction func Connection(_ sender: AnyObject) {
    let loginFunc = Login()
    loginFunc.login(username: username.text!, password: password.text!) { jsonString in
        let response = jsonString
        print(response)
        if response.range(of: "failure") == nil {
            self.performSegue(withIdentifier: "home", sender: nil)
        }
    }
}

Login:

class Login {
// the completion closure signature is (String) -> ()
func login(username: String, password: String, completion: @escaping (String) -> ()) {
    var request = URLRequest(url: URL(string: "http://myurl/web/app_dev.php/login_check")!)
    request.httpMethod = "POST"
    let postString = "_username=" + username + "&_password=" + password
    request.httpBody = postString.data(using: .utf8)
    var responseString = ""
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {                                                 // check for fundamental networking error
            print("error=\(error)")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(response)")
        }

            responseString = String(data: data, encoding: .utf8)!
            completion(responseString)
        }
        task.resume()
    }
}

It sometimes crash with the following error :

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[UIKeyboardTaskQueue waitUntilAllTasksAreFinished] may only be called from the main thread.'

Is there a better way to do it ?


回答1:


Trying this way :

 if response.range(of: "failure") == nil {
            NSOperationQueue.mainQueue().addOperationWithBlock {
                 self.performSegue(withIdentifier: "home", sender: nil)
            }
        }

swift3:

if response.range(of: "failure") == nil {
           OperationQueue.main.addOperation {
                self.performSegue(withIdentifier: "home", sender: nil)
            }
}



回答2:


As the error says you need to call perform segue in Main Thread like this

DispatchQueue.main.async {
    self.performSegue(withIdentifier: "home", sender: nil)
}


来源:https://stackoverflow.com/questions/40509159/call-performsegue-after-urlsession-shared-datatask

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!