Suhas Patil Suhas Patil - 7 months ago 135
Swift Question

Attempt to present whose view is not in the window hierarchy

I am trying to create the alert controller class in swift

//AppDelegate.swift:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.

window = UIWindow(frame:UIScreen.mainScreen().bounds)

let loginVC = ViewControllerForLogin (nibName:"ViewControllerForLogin", bundle:nil)

navigationObject = UINavigationController(rootViewController: loginVC)

window?.rootViewController = loginVC

window?.makeKeyAndVisible()
return true
}

//SPSwiftAlert.swift

class SPSwiftAlert: UIViewController {

//#MARK: - Members

internal var defaultTextForNormalAlertButton = "OK"

static let sharedObject = SPSwiftAlert()

//#MARK: Functions

func showNormalAlert(controller: UIViewController, title: String, message: String) {

// create the alert
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)

// add an action (button)
alert.addAction(UIAlertAction(title: defaultTextForNormalAlertButton, style: UIAlertActionStyle.Default, handler: nil))

// show the alert
controller.presentViewController(alert, animated: true, completion: nil)

}
}



the above class is used display the alert with provided message and
title with single button as-


SPSwiftAlert.sharedObject.showNormalAlert(self, title: "Invalid input", message: "Entered email address is not valid")


but this giving me runtime error as

Attempt to present <UIAlertController: 0x7f8c805e8e80> on <Swaft_Login_Demo.ViewControllerForLogin: 0x7f8c8042d4b0> whose view is not in the window hierarchy!


How should i resolve this ?

Answer

So, when I saw your code I dont understand the part where you put to window.rootViewController your loginVC instead of the navigation..

window?.rootViewController = navigationObject

Then, it seems you are not in the window's view hierarchy when you call your alert.

Try to write this call to the viewDidAppear: method.

override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        dispatch_async(dispatch_get_main_queue()) {
              SPSwiftAlert.sharedObject.showNormalAlert(self, title: "Invalid input", message: "Entered email address is not valid")
        }
}
Comments