警报错误并动态显示隐藏的UILabel

时间:2015-03-01 13:02:24

标签: ios swift uilabel alertview

我有两个不同的问题,

  1. 我有一个隐藏在viewDidLoad()中的Label,后来我试图将隐藏值设置为false,但它不起作用。
  2. 尝试显示提醒,但收到此错误"由于未捕获的异常终止应用' NSInvalidArgumentException',原因:'应用程序尝试以模态方式呈现活动控制器"
  3. 以下是我的代码

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

1 个答案:

答案 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)
 }
                }

            }