iosios10serviceextension

iOS: How to reach saved data of an app from inside its UNNotificationServiceExtension?


Is there any way to reach data saved in the Sandbox of an iOS app from inside its Notification-Service-Extension instance? I want to grab some data from a database before I pass on the contenhandler.

I tested from inside my

    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")
            }...

and for me it looks like the extension has its own Sandbox with its own documents folder.

The app uses the folder 'Application' while the extension uses the folder 'PluginKitPlugin', both inside '/var/mobile/Containers/Data/'.

UPDATE: Seems that it is not possible to reach the apps sandbox container.


Solution

  • From App Extension Programming Guide, App Extension can Sharing Data with Your Containing App using app groups.

    Read:

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

    Write:

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

    Also