繁体   English   中英

如何使用swift从api响应中等待登录视图的值

[英]How to wait a value from api response for login view using swift

我开始学习Swift,并且不熟悉使用swift代码的同步和异步操作。 我想在我的登录视图(viewcontroller)中,当用户输入ID,PASSWORD,然后从API请求服务时,API会比较数据库数据是否正确,如果正确返回json data => true,错误返回json data => false

我不知道如何在获得API响应后执行login()。

我已经研究了很多关于此的信息,包括NSOperationQueue ......等。

但是实施的最终结果都失败了,请有经验的人帮帮我,谢谢!

var jsonmessage: Bool? = nil

当onclickLogin将使用segue进入下一页

 @IBAction func onclickLogin(_ sender: Any) {

            Postusercheck()
            login()
}

请求api

 func Postusercheck(){
        let parameters = ["ID":txtcount.text,"Password":txtpaswoerd.text] //post request with id,password
        print(parameters)
        let url = URL(string: "http://" + apiip + "/api/user")! //change the url
        let session = URLSession.shared
        //now create the URLRequest object using the url object
        var request = URLRequest(url: url)
        request.httpMethod = "POST" //set http method as POST
        do {
            request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass
        } catch let error {
            print(error.localizedDescription)
        }
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
            guard error == nil else {
                return
            }
            guard let data = data else {
                return
            }
            do {
                if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
                    print(json)
                    self.jsonmessage = json["message"] as? Bool
                    print("Title: \(String(describing:  self.abc)))")
                    }
                } catch let error {
                print(error.localizedDescription)
                                  }
        })
                task.resume()
    }
 func login(){

    if (self.jsonmessage == true){
    }
    else if txtcount.text == "" || txtpaswoerd.text == "" {
    let alert = UIAlertController(title: "Don't empty the field", message: "Please enter again", preferredStyle: .alert)
    let ok = UIAlertAction(title: "OK", style: .default, handler: nil)

    alert.addAction(ok)
    present(alert, animated: true, completion: nil)

        }
        else
            {
                let alert = UIAlertController(title: "ID OR PASSWORD ERROR", message: "Please enter again", preferredStyle: .alert)
                let ok = UIAlertAction(title: "OK", style: .default, handler: nil)
                alert.addAction(ok)
                present(alert, animated: true, completion: nil)
            }
    }

========================更新========代码======

@IBAction func onclickLogin(_ sender: Any) {

        Postusercheck()
}

    func Postusercheck(){

        let parameters = ["ID":txtcount.text,"Password":txtpaswoerd.text] //post request with id,password
        print(parameters)
        let url = URL(string: "http://" + apiip + "/api/user")! //change the url
        let session = URLSession.shared
        //now create the URLRequest object using the url object
        var request = URLRequest(url: url)
        request.httpMethod = "POST" //set http method as POST
        do {
            request.httpBody = try JSONSerialization.data(withJSONObject: parameters, options: .prettyPrinted) // pass
        } catch let error {
            print(error.localizedDescription)
        }
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
            guard error == nil else {
                return
            }
            guard let data = data else {
                return
            }
            do {
                if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
                    print(json)
                    self.jsonmessage = json["message"] as? Bool
                    self.login()

                    }
                } catch let error {
                print(error.localizedDescription)
                                  }
        })
                task.resume()
    }
func login(){
    if (self.jsonmessage == true){
        //Navigate to the another view controller
        let mainStoryboard = UIStoryboard.init(name: "Main", bundle: nil)
        let anotherViewController = mainStoryboard.instantiateViewController(withIdentifier: "AnotherViewController")
        self.navigationController?.pushViewController(anotherViewController, animated: true)
    }
    else if txtcount.text == "" || txtpaswoerd.text == "" {
        let alert = UIAlertController(title: "Don't empty the field", message: "Please enter again", preferredStyle: .alert)
        let ok = UIAlertAction(title: "OK", style: .default, handler: nil)

        alert.addAction(ok)
        present(alert, animated: true, completion: nil)
    }
    else
    {
        let alert = UIAlertController(title: "ID OR PASSWORD ERROR", message: "Please enter again", preferredStyle: .alert)
        let ok = UIAlertAction(title: "OK", style: .default, handler: nil)
        alert.addAction(ok)
        present(alert, animated: true, completion: nil)
    }
}

当我尝试新代码时。

我已经取消了原来的segue连接。 我在我想要的页面上将Storboard ID设置为AnotherViewController,但是当成功验证帐户密码后,他不会转到下一页。

他只是停在原始页面(帐户密码验证成功后)如果我输入了错误的帐户密码,它仍会收到错误消息。 这个功能很有用。

在URLSession的完成处理程序中进行函数调用,如下所示:

    let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in
                guard error == nil else {
                    return
                }
                guard let data = data else {
                    return
                }
                do {
                    if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
                        print(json)
                        self.jsonmessage = json["message"] as? Bool
                        self.login()
                        print("Title: \(String(describing:  self.abc)))")
                        }
                    } catch let error {
                    print(error.localizedDescription)
                                      }
            })

当您调用Postusercheck时,您必须从按钮的IBAction原因中删除登录调用,它将进行webservice调用,并且它不会等待响应,因为session.dataTask是异步的。 因此执行将返回到IBAction并且虽然您没有收到Web服务响应但是您不知道用户名和密码是否正确,因此将调用login() 因此,您必须从按钮单击操作中删除登录调用,如下所示:

@IBAction func onclickLogin(_ sender: Any) {

            Postusercheck()
}

更改登录功能如下:

func login(){

    if (self.jsonmessage == true){
       //Navigate to the another view controller
       let mainStoryboard = UIStoryboard.init(name: "Main", bundle: nil)
       let anotherViewController = mainStoryboard.instantiateViewController(withIdentifier: "AnotherViewController")
       self.navigationController?.pushViewController(anotherViewController, animated: true)    
    }
    else if txtcount.text == "" || txtpaswoerd.text == "" {
    let alert = UIAlertController(title: "Don't empty the field", message: "Please enter again", preferredStyle: .alert)
    let ok = UIAlertAction(title: "OK", style: .default, handler: nil)

    alert.addAction(ok)
    present(alert, animated: true, completion: nil)

        }
        else
            {
                let alert = UIAlertController(title: "ID OR PASSWORD ERROR", message: "Please enter again", preferredStyle: .alert)
                let ok = UIAlertAction(title: "OK", style: .default, handler: nil)
                alert.addAction(ok)
                present(alert, animated: true, completion: nil)
            }
    }

这里确保你在故事板中有一个名为“Main”的视图控制器,其中Storyboard Id为“AnotherViewController”,否则它将无效。

另一种导航选项是通过故事板中的segue。 下面是一个很好的教程,可以学习故事板的精彩内容。

https://www.raywenderlich.com/464-storyboards-tutorial-for-ios-part-1

还有一件事是Postusercheck()不是那么好的函数名。 有关swift广泛使用的命名约定的最佳实践,请参阅以下指南:

https://github.com/raywenderlich/swift-style-guide

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM