我有两个不同的问题,
以下是我的代码
class HomeViewController: UIViewController ,UITextFieldDelegate {
@IBOutlet weak var userName: UITextField!
@IBOutlet weak var passWord: UITextField!
@IBOutlet weak var errorMessage: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
self.errorMessage.hidden = true
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func login(sender: AnyObject) {
let alertController = UIAlertController(title: "Error", message:
"Wrong username or password", preferredStyle: UIAlertControllerStyle.Alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.Default,handler: nil))
let url = NSURL(string: "myurl")
let task = NSURLSession.sharedSession().dataTaskWithURL(url!) {(data, response, error) in
println(NSString(data: data, encoding: NSUTF8StringEncoding))
var error: NSError?
let jsonData: NSData = data /* get your json data */
let json = NSJSONSerialization.JSONObjectWithData(jsonData, options: nil, error: &error) as NSDictionary
if let login: AnyObject = json["login"] {
if (login as NSObject == 0){
self.errorMessage.hidden = false
self.presentViewController(alertController, animated: true, completion: nil)
}
}
}
task.resume()
}
答案 0 :(得分:1)
好的,最后我使用dispatch_async(dispatch_get_main_queue()){}解决了这个问题,所以if语句将是这样的
if let login: AnyObject = json["login"] {
if (login as NSObject == 0){
dispatch_async(dispatch_get_main_queue()) {
self.errorMessage.hidden = false
self.presentViewController(alertController, animated: true, completion: nil)
}
}
}