Search code examples
swiftuilocalnotificationuialertcontrolleruialertaction

How to get a UIAlertAction from UIAlertcontroller presented when registeringForNotifications


I want to make some switches on a view controller dependant on whether a user has allowed / not to register for notifications. The very first time this view loads and

appDelegate.registerForNotifications(UIApplication.sharedApplication())

is called in ViewDidLoad the AlertController is shown and the viewController completes its layout as expected, hence missing any dependency on if the user allows / not the notifications.

I know I could present the register alert as soon as the app launches, but I want to wait to ask for permission in this view controller as it is only relevant in this view and not others before it.

Is there any way of capturing the UIAlertAction before viewWillAppear is called?


Solution

  • Is there any way of capturing the UIAlertAction before viewWillAppear is called?

    No, nor should there be. You do not do things before viewDidLoad, viewWillAppear, and so forth. Your job in these methods is to respond as needed (for example, by doing initializations) and then get out of the way, just as fast as possible. You must not delay the appearance of the view controller in any way.

    Instead, rethink your architecture.

    The view controller's view is going to appear. So just let it! If you are concerned that, say, a button should not be enabled if the user disallows registration, then start out with the button disabled and only enable it after you know (or learn in the alert action's handler) that it is now allowed.

    Or, if this view controller depends entirely on the user allowing registration, move registration to an earlier phase of your app, and don't even allow the user to come here without it!