My application has a menu with option "Contacts". When user selects Contacts for the first time, application asks user permission to use device Contacts. If user allows access, opens a view controller with contacts of his/her device, if he doesn't, nothing happens. After that every time they select "Contacts" option, it heads to Device Settings where they should allow access to contacts or dismiss it. When they allow access and go back to the app, I want it to open the view controller with contacts, but it doesn't.

I've tried to use NotificationCenter with didBecomeActiveNotification option, but it does not seem to help.

func checkPermissionToDeviceContacts() {
    switch CNContactStore.authorizationStatus(for: .contacts) {
    case .notDetermined:
        self.requestContactsAccess()
    case .authorized:
        self.openContactsViewController()
    case .denied:
        self.headToSettingsOfPermissions()
    default: return
    }
}

func headToSettingsOfPermissions() {
    if let bundleId = Bundle.main.bundleIdentifier,
        let url = URL(string: "\(UIApplication.openSettingsURLString)&path=APPNAME/\(bundleId)")
    {
        UIApplication.shared.open(url, options: [:], completionHandler: nil)
    }
    self.setupNotifications()
}

func setupNotifications() {
    NotificationCenter.default.addObserver(self, selector: #selector(self.applicationDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
}

@objc func applicationDidBecomeActive() {
    if CNContactStore.authorizationStatus(for: .contacts) == .authorized {
        self.openContactsViewController()
    }
    NotificationCenter.default.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil)
}

I also cannot debug it, because when Device Settings are opened and I change the access status of Contacts, my console prints a message "Message from debugger: Terminated due to signal 9".

The problem is that the selector function works when I do not change the authorization status, but when I do, it does not work anyway.

P.S. This is my first time to use NotificationCenter, maybe I do not use it properly.

1

There are 1 best solutions below

2
On

NotificationCenter sends always the affected notification as parameter, you have to declare

@objc func applicationDidBecomeActive(_ notification : Notification) {

and remove self in the selector parameter

NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)