我的函数返回String但我无法解析它?任何想法为什么?

时间:2017-12-04 15:44:35

标签: ios json swift function class

我已经开了一个名为db_conn的课程,在这个课程中我有以下功能:

public func login (email : String , password : String ) -> String  {
    var result = ""
    let url = URL(string: API.url_login.rawValue)!
    var request = URLRequest(url: url)
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.httpMethod = "POST"
    let postString = "email=\(email)&password=\(password)"
    request.httpBody = postString.data(using: .utf8)
    let task = URLSession.shared.dataTask(with: request) { data, response, error in


        guard let data = data, error == nil else {
            print("error=\(String(describing: error))")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("\(String(describing: response))")
        }

        let responseString = String(data: data, encoding: .utf8)
        result = String(responseString!)
        //print("responseString = \(responseString!)")
    }
    task.resume()


    return result
}

然后在我的登录viewController类中我尝试使用它像==>

 @IBAction func login_button_action(_ sender: UIButton) {

       let email = email_text.text
       let passw0rd = password_text.text


        if (email != "" && passw0rd != ""){
            let db_connect = db_conn()
            if  (db_connect.login(email: email!, password: passw0rd!) == nil ){

                print("it's empty ")

            }else {

                print("not empty \(db_connect.login(email: email!, password: passw0rd!))")

            }


        }else {

            let alert = UIAlertController(title: "Error", message: "Dont leave any of the spaces blank , they all must be filled up , try again ! ", preferredStyle: .alert)
            alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.default, handler: nil))
            self.present(alert, animated: true, completion: nil)
        }

当我运行项目时,它表示db_connect.login(email: email!, password: passw0rd!)的值不是空的,但它不打印出来。 (但是在我的db_conn calss中,我可以轻松打印responseString,并以String格式获取返回的JSON。 知道我在哪里弄错了吗?我怎么可能解决它?

1 个答案:

答案 0 :(得分:1)

使用URLSession发出网络请求是异步运行的,这意味着iOS将其置于后台线程并在下载完成之前立即继续当前线程。因此,当您return result时,它仍然是一个空字符串。你可能想要做的是将完成结束传递给你的login方法,并在完成下载后用相关数据调用