我正在尝试用 swift 编写一个登录函数,该函数将 HTTP POST 请求发送到网页,然后接收一个 JSON 对象作为响应。那部分我工作得很好;虽然,我对我的代码有点困惑。我从在线教程中获得了部分内容,但我并不完全理解。我想要做的是在登录成功时触发到另一个 View 的 segue。此外,当登录失败时,我想显示一个显示“用户名和密码不匹配”的 UILabel。有人可以帮助解释我编写的代码并让我知道如何更好地实现它吗?谢谢。
View Controller :
class ViewController: UIViewController {
@IBOutlet var _username: UITextField!
@IBOutlet var _password: UITextField!
@IBOutlet var _button: UIButton!
@IBOutlet var errorText: UILabel!
@IBAction func loginButtonPress(_ sender: Any) {
let username = _username.text
let password = _password.text
if(username == "" || password == "") {
return
}
DoLogin(username: username!, password: password!)
}
登录函数:
func DoLogin(username: String, password: String) {
let myUrl = URL(string: "http://MYURL.com");
var request = URLRequest(url:myUrl!)
request.httpMethod = "POST"// Compose a query string
let postString = "username=\(username)&password=\(password)";
request.httpBody = postString.data(using: String.Encoding.utf8);
let task = URLSession.shared.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
if error != nil
{
print("error=\(error)")
return
}
// Print out response object
print("response = \(response)")
//Convert response sent from a server side script to a NSDictionary object:
do {
let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
if let parseJSON = json {
// Access value of username, name, and email by its key
let usernameValue = parseJSON["username"] as? String
let nameValue = parseJSON["name"] as? String
let emailValue = parseJSON["email"] as? String
print("usernameValue: \(usernameValue)")
print("nameValue: \(nameValue)")
print("emailValue: \(emailValue)")
if(usernameValue != nil && nameValue != nil && emailValue != nil) {
//The Login WAS SUCCESSFUL
//This is where I want to perform a segue to another view (like this)
//performSegue(withIdentifier: "loginToMain", sender: self) //This does not work
//Error above is (implicit use of 'self' in closuer; use 'self.' to make capture semantics explicit
}
} else {
//Username and Password do not match
print("Username and password do not match. Please Try again");
//This is what I want to do
self.errorText.isHidden = false
//But nothing happens to the errorText UILabel
}
} catch {
print(error)
}
}
task.resume()
}
最佳答案
用 self.performSegue 代替 performSegue
并为这两个添加一个 DispatchQueue 包装器
DispatchQueue.main.async
{
self.performSegue(withIdentifier: "loginToMain", sender: self)
}
..
DispatchQueue.main.async {
self.errorText.isHidden = false
}
当您调用 URLSession 时,其完成处理程序中的代码在后台线程中运行,但 GUI 必须在主线程中更新。添加 DispatchQueue.main.async 会在主线程中更新这些内容。
关于ios - Swift 3 登录函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42046101/