ios - Swift 3 登录函数

标签 ios swift swift3

我正在尝试用 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/

相关文章:

ios - 获取 naturalSize 并列出分辨率视频 m3u8

ios - 根据某种逻辑在 TableView 中显示某个单元格

ios - 删除代码后触发的本地通知

ios - 如何在 ios 中从 appdelegate 呈现不同的 View Controller

ios - 没有 SKTNavigationManager 的 Skobbler 后台模式

objective-c - SVPullToRefreshPositionBottom 属性未在 swift 3.0 中设置

ios - 上传Multipart swift图片上传内部服务器错误500响应

ios - 如何在 Swift 中识别我们来自哪个 View Controller

ios - 哪个是抑制 "unused variable"警告的最佳方法

iphone - 从付费应用程序切换到具有自动续订订阅的免费应用程序