iOS:如何从应用程序的 UNNotificationServiceExtension 内部获取应用程序的已保存数据?

标签 ios ios10 serviceextension

是否有任何方法可以从 iOS 应用程序的 Notification-Service-Extension 实例内部获取保存在沙盒中的数据?我想在传递 contenhandler 之前从数据库中获取一些数据。

我从我的内部测试

    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
            ...
            print("NotificationService didReceive UNNotificationRequest, contentHandler: \(contentHandler)")

            let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
            let filePath = "\(documentsPath)/Database.db"

            print("  documentsPath: \(filePath)")

            let fileManager = FileManager.default
            var isDir : ObjCBool = false
            if fileManager.fileExists(atPath: filePath, isDirectory:&isDir) {
                if isDir.boolValue {
                    print("  file exists and is a directory")

                } else {
                    print("  file exists and is a NOT a directory")
                }
            } else {
                print("file does not exist")
            }...

对我来说,扩展程序似乎有自己的沙盒和自己的文档文件夹。

应用程序使用文件夹“Application”,而扩展程序使用文件夹“PluginKitPlugin”,它们都在“/var/mobile/Containers/Data/”中。

更新:似乎无法访问应用沙箱容器。

最佳答案

来自App Extension Programming Guide,App Extension can Sharing Data with Your Containing App使用应用程序组。

阅读:

if let defaults = UserDefaults(suiteName: "my.app.group") {
    if let value = defaults.value(forKey: "key") {
        NSLog("\(value)")
    }
}

写:

if let defaults = UserDefaults(suiteName: "my.app.group") {
    defaults.set("value", forKey: "key")
}

还有

  • MMWormhole : 在 iOS 应用程序和扩展程序之间传递消息。
  • Wormhole : 在 iOS 应用程序和扩展程序之间传递消息的一种更优雅的方式。

关于iOS:如何从应用程序的 UNNotificationServiceExtension 内部获取应用程序的已保存数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42132509/

相关文章:

ios - TextEdit 字段输入在 iOS10 上挂起

使用 UIImagePickerController 时 iOS 10 错误 [访问] <private>

ios - 通知服务扩展不工作

ios - UNNotificationServiceExtension 中的附件文件 URL 无效

ios - 尝试使用 for 循环并将其替换为某个值

ios - 解析 iOS Swift 中的 SaveEventually 问题

ios - OpenCV MatToUIImage 导致内存泄漏

swift - 本地通知的通知服务扩展

ios - iPhone和iPad的iOS图像大小

jquery - 手动触发专注于输入 Iphone 问题