【发布时间】:2017-12-04 15:44:35
【问题描述】:
我创建了一个名为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。
知道我在哪里犯错了吗?我怎么可能修复它?
【问题讨论】:
-
请了解异步处理。
-
“但是在我的 db_conn calss 中,我可以轻松地打印 responseString 并以字符串格式获得返回的 JSON”:您能否在
return result之前添加打印,并检查它是否在 @987654327 之前打印@。您在这里缺少异步逻辑。
标签: ios json swift function class