获取网络请求后,无法在IBAction中执行任何代码

时间:2017-07-11 05:39:09

标签: ios swift networking ibaction

在我确认从Udacity API获取会话ID后,我尝试转换到新的segue。但是,在此之后我无法运行任何代码。将打印会话ID和所有信息,但之后不会完成任何操作。我的功能有什么问题吗?我尝试执行UIUpdates然后尝试打印“Hello”,但这也没有用。下面是一些代码以及我的GitHub配置文件。 https://github.com/SteveBurgos95/UdacityMapProject

    @IBAction func loginButton(_ sender: Any) {
UdacityClient.sharedInstance().loginWithUsername(emailTextField.text!, password: passwordTextField.text!){ (success, error) in
    performUIUpdatesOnMain {
        if success {
            print("Hello")
        } else {
            print("Hey")
        }
    }
}

private func completeLogin() {
emailTextField.text = ""
let controller = storyboard!.instantiateViewController(withIdentifier: "TableMapViewController") as! UINavigationController
present(controller, animated: true, completion: nil)

3 个答案:

答案 0 :(得分:2)

在我看来,当dataTask结束时(无论是出错还是成功),你都不会在UdacityClient.swift中调用你的完成处理程序?

这应该是这样的:

let task = session.dataTask(with: request as URLRequest) { data, response, error in

    // Make sure there is no error, or else
    guard error == nil else { // Handle error…

      completionHandler(false, error?.localizedDescription)
      /*
         func sendError(_ error: String) {
         print(error)
         let userInfo = [NSLocalizedDescriptionKey : error]
         completionHandlerForGET(nil, NSError(domain: "taskForGETMethod", code: 1, userInfo: userInfo))
        */
        return
    }

    completionHandler(true, nil)
}

答案 1 :(得分:0)

查看代码后,UI未获得更新,因为您尚未在sucess中实施UdacityClient.swift块。 sucess阻止/关闭escapes。所以你不会在

中收到回调

UdacityClient.sharedInstance().loginWithUsername(emailTextField.text!, password: passwordTextField.text!){

答案 2 :(得分:-1)

更改下面的功能

     func loginWithUsername(_ username: String, password: String, completionHandler: @escaping (_ success: Bool, _ errorMessage: String?) -> Void ) {
        let request = NSMutableURLRequest(url: URL(string: "https://www.udacity.com/api/session")!)
        request.httpMethod = "POST"
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")

        request.httpBody = "{\"udacity\": {\"username\": \"\(username)\", \"password\": \"\(password)\"}}".data(using: String.Encoding.utf8)

        let session = URLSession.shared
        let task = session.dataTask(with: request as URLRequest) { data, response, error in
            if error != nil 
                // Handle error…
              /*
                 func sendError(_ error: String) {
                 print(error)
                 let userInfo = [NSLocalizedDescriptionKey : error]
                 completionHandlerForGET(nil, NSError(domain: "taskForGETMethod", code: 1, userInfo: userInfo))
                */

                return
            }
           completionHandler(true,nil)
            let range = Range(5..<data!.count)
            let newData = data?.subdata(in: range) /* subset response data! */
            print(NSString(data: newData!, encoding: String.Encoding.utf8.rawValue)!)
        }
        task.resume()
        }