gpt4 book ai didi

ios - 如何使用 swift 等待登录 View 的 api 响应值

转载 作者:行者123 更新时间:2023-11-29 05:42:06 29 4
gpt4 key购买 nike

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

我不知道如何让我的login()在收到API响应后执行。

我研究了很多这方面的资料,包括 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)
}
})

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

@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)
}
}

这里请确保 Storyboard中有一个名为“Main”的 View Controller , Storyboard ID 为“AnotherViewController”,否则它将无法工作。

另一个导航选项是通过 Storyboard 中的 Segues。以下是一个很棒的教程,可帮助您了解有关 Storyboard的精彩内容。

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

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

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

关于ios - 如何使用 swift 等待登录 View 的 api 响应值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56457040/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com