0

I have 2 different problems ,

  1. I have a Label which is hidden in the viewDidLoad() and later i'm trying to set the hidden value false but its not working .
  2. Trying to show alert but getting this error "Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Application tried to present modally an active controller "

Here is my code below

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()
    }
Raquibul Islam
  • 182
  • 1
  • 12

1 Answers1

1

Ok , finally i solved this problem using dispatch_async(dispatch_get_main_queue()) { } so the if statement will be like this

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

            }  
Raquibul Islam
  • 182
  • 1
  • 12
  • Just ran into the same sort of issue, myself! Calling GUI code from a task requires dispatch_async(dispatch_get_main_queue()), thanks a bunch! – Casey Murray Sep 28 '16 at 22:31