Search code examples
iosswiftuiviewcontrolleronresume

Event called in UIViewController when return from a dialog?


Does an event exist in UIViewController called when you return from a dialog?

I'm asking for notification permission doing this:

let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound, .badge])

I need to override an event in UIViewController to do some stuff when that dialog is not present anymore, so when the screen has recovered the focus. That is exactly the behaviour onResume does in Android.

I tried with this:

NotificationCenter.default.addObserver(self, selector: #selector(onResume), name:
        UIApplication.willEnterForegroundNotification, object: nil)
@objc func onResume() {

}

and with this:

override func viewWillAppear(animated: Bool) {}

None of these functions are called when the dialog is closed.


Solution

  • The only way you can know that alert disappeared, is from completion handlers. In this case:

    center.requestAuthorization(options: [.alert, .sound, .badge]) { success, error in
        // alert disappeared
    }
    

    Or async version:

    do {
        let success = try await center.requestAuthorization(options: [.alert, .sound, .badge])
    } catch {
    }
    // alert disappeared