gpt4 book ai didi

ios - 应该使用标识符执行 segue - 错误

转载 作者:行者123 更新时间:2023-11-30 14:17:48 25 4
gpt4 key购买 nike

我正在使用shouldPerformSegueWithIdentifier方法控制何时执行segue。

  override func shouldPerformSegueWithIdentifier(identifier: String!, sender: AnyObject?) -> Bool {

if identifier == "login" {
if loginSuccess != true {

var alert = UIAlertController(title: "Alert", message: "Please enter correct login details", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)

return false
}
}

return true
}

我在类的开头声明了 loginSuccess 变量,如下所示:

   var loginSuccess:Bool? 

当 API 通过以下方式成功验证用户登录详细信息时,我将此 bool 变量更改为 true:

  self.loginSuccess = true

以上行位于 if 语句之后,用于检查 API 返回的 JSON 是否不为空。

我的问题是,当我运行代码并在应用程序中输入登录详细信息并单击登录按钮时,它总是第一次拒绝登录详细信息,当我单击登录按钮时第二次执行segue。无论我的登录详细信息是否完美,第一次点击总是被拒绝,第二次点击被接受,segue 被处理。

我认为当它第一次运行 segue 代码时,它会将“loginSuccess”的初始值视为 false,这就是它拒绝它的原因。

我该如何解决这个问题。它与 bool 变量有关。

完整代码:

 import UIKit

class ViewController: UIViewController {

var loginSuccess:Bool?

@IBOutlet weak var password: UITextField!
@IBOutlet weak var emailAdd: UITextField!


@IBAction func loginUser(sender: AnyObject) {

var x:String = password.text
var y:String = emailAdd.text

var request = NSMutableURLRequest(URL: NSURL(string: "http://myAPIlink.com/login")!)
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"

var params = ["email":"\(y)", "password":"\(x)"] as Dictionary<String, String>

var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil, error: &err)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
println("Response: \(response)")
var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Body: \(strData)")
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary

// Did the JSONObjectWithData constructor return an error? If so, log the error to the console
if(err != nil) {

println(err!.localizedDescription)
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: '\(jsonStr)'")

}
else {

// The JSONObjectWithData constructor didn't return an error. But, we should still
// check and make sure that json has a value using optional binding.

if let parseJSON = json {

// CHANGE THE loginSuccess Boolean HERE
self.loginSuccess = true

// Okay, the parsedJSON is here, let's get the value for 'success' out of it

var fullname = parseJSON["fullname"] as! String
println("Succes: \(fullname)")

var region = parseJSON["region"] as! String
println("Region: \(region)")

var uTarget = parseJSON["target"] as! String
println("Target: \(uTarget)")


}
else {
// Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: \(jsonStr)")

}
}
})

task.resume()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "podcastbg.jpg")!)

}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}



override func shouldPerformSegueWithIdentifier(identifier: String!, sender: AnyObject?) -> Bool {

if identifier == "login" {
if loginSuccess != true {

var alert = UIAlertController(title: "Alert", message: "Please enter correct login details", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)

return false
}
}

return true
}
}

如果您需要更多信息来回答问题,请告诉我。提前致谢。

最佳答案

我会稍微改变一下你的代码:

  1. 用户应输入用户名和密码
  2. 对您的服务进行(异步)调用(向用户显示旋转图标)
  3. 如果结果有效 -> 更改 segue

我不会使用

shouldPerformSegueWithIdentifier

只是:

  if let parseJSON = json {

// CHANGE THE loginSuccess Boolean HERE

self.performSegueWithIdentifier("loginSuccessSegue", sender: nil)

或者以其他方式向用户显示错误消息。

如果您愿意,可以设置“登录成功”值,然后使用

进行检查
   prepareForSegue

关于ios - 应该使用标识符执行 segue - 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30914507/

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