Reputation: 1461
How to detect when user Enable or Disable extension in Safari preferences? I‘m interesting on to get notification immideatly when user Enable/Disable my extension.
Upvotes: 1
Views: 449
Reputation: 614
You can get the state of your Safari App Extension using the SFSafariExtensionManager and the getStateOfSafariExtension(withIdentifier:completionHandler:) method:
SFSafariExtensionManager.getStateOfSafariExtension(withIdentifier: "com.example") { state, error in
guard let state = state, error == nil else { return }
if state.isEnabled {
// todo
} else {
// todo
}
}
You wrote that you want to be notified about the status change immediately. To my knowledge there is no notification for this that you can observe. Therefore, you should write more about why you want to be notified immediately.
If you want to update your UI, you should not observe the status of your extension, but react when your app will become active. You can do that for example like this:
NotificationCenter.default.addObserver(self, selector: #selector(detectStateOfSafariAppExtension), name: NSApplication.willBecomeActiveNotification, object: nil)
If you want to run a background operation, you have to implement a silly workaround. Because no notification is sent, you must poll. This should be implemented as efficiently as possible and depends heavily on your use case. Unfortunately, there is no better way. You can use a timer for example:
Timer(timeInterval: 5.0, repeats: true) { _ in
// todo
}
Please be aware that polling is not a good solution. Unfortunately, I don't know the reason why you want to be informed immediately and therefore I can't give you a better alternative.
Upvotes: 3