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

hea*_*kit 5 ios ios10 serviceextension

有没有办法从Notification-Service-Extension实例中获取保存在iOS应用程序Sandbox中的数据?我想在传递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")
            }...
Run Code Online (Sandbox Code Playgroud)

对我来说,看起来扩展程序有自己的Sandbox和自己的文档文件夹.

该应用程序使用文件夹'Application',而扩展名使用文件夹'PluginKitPlugin',都在'/ var/mobile/Containers/Data /'中.

更新:似乎无法访问应用程序沙箱容器.

Win*_*ter 5

从 App Extension Programming Guide 中,App Extension 可以使用应用程序组与您的包含应用程序共享数据

读:

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

写:

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

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