我正在使用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以下列方式成功验证用户登录详细信息时,我将此布尔变量更改为 true :
self.loginSuccess = true
上面的行放在if语句之后,该语句检查API返回的JSON是否为空。
我的问题是,当我运行代码并在应用程序中输入我的登录详细信息并单击登录按钮时,它总是第一次拒绝登录详细信息以及单击登录按钮时第二次执行segue。无论我的登录详细信息是否完美,第一次点击总是被拒绝,第二次点击被接受处理了segue。
我认为当它第一次运行segue代码时,它会将“loginSuccess”的初始值视为false,这就是它拒绝它的原因。
我该如何解决这个问题。它与布尔变量有关。
完整代码:
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
}
}
如果您需要更多信息来回答这个问题,请告诉我。 提前谢谢。
答案 0 :(得分:0)
发布您的登录按钮代码。
听起来您的登录过程是异步的,在触发segue之前,您不会等到它完成。您需要将其编写为使用完成块。
听起来像是一个糟糕的设计。
你在做什么是行不通的。
从登录按钮中删除segue。
在完成处理程序内的loginUser方法中添加代码,该代码在登录完成后在主线程上调用您的segue。
答案 1 :(得分:0)
我会稍微改变你的代码:
我不会用
shouldPerformSegueWithIdentifier
只需:
if let parseJSON = json {
// CHANGE THE loginSuccess Boolean HERE
self.performSegueWithIdentifier("loginSuccessSegue", sender: nil)
或以其他方式向用户显示错误消息。
如果您愿意,可以设置&#34; Loginsuccess&#34;值,并用
检查 prepareForSegue
答案 2 :(得分:0)
我没有看到您的登录按钮代码中调用shouldPerformSegueWithIdentifier
的位置