0

I am using following code to login users first user enters password and id then using post request I am sending this information to the server.

let alert = UIAlertController(title: nil, message: "Please wait...", preferredStyle: .alert)
        let message2  = "Please wait..."
        var messageMutableString = NSMutableAttributedString()
        messageMutableString = NSMutableAttributedString(string: message2 as String, attributes: [NSFontAttributeName:UIFont(name: "HelveticaNeue-Bold",size: 15.0)!])
        alert.setValue(messageMutableString, forKey: "attributedMessage")
        let loadingIndicator = UIActivityIndicatorView(frame: CGRect(x: 10, y: 5, width: 50, height: 50))
        loadingIndicator.hidesWhenStopped = true
        loadingIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
        loadingIndicator.startAnimating();



        alert.view.addSubview(loadingIndicator)
        present(alert, animated: true, completion: nil)

        if Reachability.isConnectedToNetwork() == true {

            var postString = GlobalVariable.globalIpAdress

            postString.append("&userid=")
            postString.append(userId.text!)
            postString.append("&password=")
            postString.append(password.text!)
            postString.append("&parola=")

            let urlString = postString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlFragmentAllowed)
            var request = URLRequest(url: URL(string:urlString!)!)
            request.httpMethod = "POST"
            request.timeoutInterval=10
            message="Request timed out"


            let task = URLSession.shared.dataTask(with: request) { data, response, error in

                DispatchQueue.main.async {
                    self.dismiss(animated: false, completion: nil)
                }

                guard let data = data, error == nil else {
                    print("error=\(String(describing: error))")
                    DispatchQueue.main.async {
                        let alert = UIAlertView(title: "Uyarı!", message: self.message, delegate: nil, cancelButtonTitle: "OK")
                        alert.show()
                    }
                    return;
                }



                if let json = (try? JSONSerialization.jsonObject(with: data, options: [])) as? NSDictionary

                {
                    print(json)
                    if (json["error"] as? String) != nil {}

                    if let messages = json["messages"] as? NSArray{

                        for item in messages {

                            if let description = item as? AnyObject {

                                if let text = description["text"] as? String {
                                    self.message = text
                                }
                            }
                        }
                    }

                    if let tokenTemp = json["token"] as? String {

                        self.success=true
                        GlobalVariable.globalToken = tokenTemp
                    }
                }

                if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
                    print("statusCode should be 200, but is \(httpStatus.statusCode)")
                    print("response = \(String(describing: response))")
                }



                let responseString = String(data: data, encoding: .utf8)
                print("responseString = \(String(describing: responseString))")

                DispatchQueue.main.async {

                    if(self.success == true){
                        self.performSegue(withIdentifier: "secondVC", sender: self)
                    } else {
                        let alert = UIAlertView(title: "Warning!", message: self.message, delegate: nil, cancelButtonTitle: "OK")
                        alert.show()

                    }

                }
            }

            task.resume()
        }
        else{
            print("Internet connection FAILED")
            let alert = UIAlertView(title: "No Internet Connection", message: "Make sure your device is connected to the internet.", delegate: nil, cancelButtonTitle: "OK")
            alert.show()

        }

First of all, I am adding indicator view for login screen and then, as soon as token came my Bool success variable is becoming true and I am dismissing the activity indicator then it needs to be gone next screen but it is not working right now and also I am getting following error.

Warning: Attempt to present UITabBarController on UIAlertController: whose view is not in the window hierarchy!

What could be the reason where am I doing wrong?

Faysal Ahmed
  • 7,501
  • 5
  • 28
  • 50
atalayasa
  • 3,310
  • 25
  • 42
  • 3
    try to change `self.dismiss(animated: false, completion: nil)` with `alert.dismiss(animated: true, completion: nil)` – mugx Feb 05 '18 at 06:21

1 Answers1

1

I think the error itself explains the issue here:

Attempt to present UITabBarController on UIAlertController: whose view is not in the window hierarchy!

As you are presenting the UIAlertController in this line of code :

present(alert, animated: true, completion: nil)

but you are not dismissing it and trying to performSegue on UIAlertController:

self.performSegue(withIdentifier: "secondVC", sender: self)

Dismiss the UIAlertController whenever you present it.

Refer this :

Amit
  • 4,837
  • 5
  • 31
  • 46
  • So you mean just after present shall I dismiss it ? Could you please make changes on code because I still get the error. – atalayasa Feb 07 '18 at 06:29
  • Dismiss it when you are done with it. Like just before `performSegue` or any other event or process you are going to perform. – Amit Feb 07 '18 at 06:33