简体   繁体   English

如何检测用户何时在 Safari 首选项中启用或禁用扩展

[英]How to detect when user Enable or Disable extension in Safari preferences

How to detect when user Enable or Disable extension in Safari preferences?如何检测用户何时在 Safari 首选项中启用或禁用扩展? I'm interesting on to get notification immideatly when user Enable/Disable my extension.当用户启用/禁用我的扩展程序时,我很高兴立即收到通知。

You can get the state of your Safari App Extension using the SFSafariExtensionManager and the getStateOfSafariExtension(withIdentifier:completionHandler:) method:您可以使用SFSafariExtensionManagergetStateOfSafariExtension(withIdentifier:completionHandler:)方法获取 Safari 应用程序扩展的 state:

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.如果你想更新你的 UI,你不应该观察你的扩展程序的状态,而是在你的应用程序激活时做出反应。 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.不幸的是,我不知道您为什么要立即收到通知,因此我无法为您提供更好的选择。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM