【问题标题】:iOS: How to reach saved data of an app from inside its UNNotificationServiceExtension?iOS:如何从应用程序的 UNNotificationServiceExtension 内部访问已保存的数据?
【发布时间】:2017-02-09 09:16:03
【问题描述】:

有什么方法可以从 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/”内。

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

【问题讨论】:

    标签: ios ios10 serviceextension


    【解决方案1】:

    根据 App Extension Programming Guide,App Extension 可以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 应用和扩展程序之间传递消息的一种更优雅的方式。

    【讨论】:

    • 这很有趣,谢谢。但是当我想访问我的应用程序数据库时,我需要将它复制到共享容器中——而不是我想要的解决方案。但确实很有趣。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 2011-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多