0

我有一个UNNotificationServiceExtension将视频和图像下载到Documents目录以供采用UNNotificationContentExtension. 我想删除不再被任何通知使用的媒体文件。我不知道该怎么做。

  • 我试图删除我的 AppDelegate 中的文件,但我相信根据本文档的“与包含的应用程序共享数据”部分,UNNotificationServiceExtension它有自己的目录: https ://developer.apple.com/library/archive/documentation/General /Conceptual/ExtensibilityPG/ExtensionScenarios.html,所以我无法从我的主应用程序访问这些文件。它们在不同的容器中。Documents
  • 我不想创建一个应用组来在应用和扩展程序之间共享数据,这样我就可以删除未使用的文件。
  • 我不想删除 中未使用的文件UNNotificationServiceExtension,因为扩展程序完成工作的时间有限,如果我尝试下载文件并删除其他文件,它可能会超时。

我认为最好的选择是检查任何传递的通知需要哪些文件,并删除通知服务扩展Documents目录中不需要的文件。我对此的担忧是,UNNotificationServiceExtension它只给了很短的时间,在此期间它必须完成所有工作,之后它将超时。

所以,我的问题是,“这是从通知服务扩展中清理未使用文件的正确方法,还是有更好的方法?”

4

1 回答 1

0

感谢 manishsharma93,我能够实施一个很好的解决方案。我现在将文件存储在主应用程序和通知服务扩展共享的目录中。我首先必须使用此处找到的信息设置共享应用程序组:https ://developer.apple.com/library/archive/documentation/Miscellaneous/Reference/EntitlementKeyReference/Chapters/EnablingAppSandbox.html#//apple_ref/doc/ uid/TP40011195-CH4-SW19

然后在我的 AppDelegate 中,我添加了这个私有函数,我在方法的末尾调用它applicationDidFinishLaunching(_:)

// I call this at the end of the AppDelegate.applicationDidFinishLaunching(_:) method
private func clearNotificationMedia() {
    // Check to see if there are any delivered notifications. If there are, don't delete the media yet,
    // because the notifications may be using them. If you wanted to be more fine-grained here,
    // you could individually check to see which files the notifications are using, and delete everything else.
    UNUserNotificationCenter.current().getDeliveredNotifications { (notifications) in
        guard notifications.isEmpty else { return }

        let fileManager = FileManager.default

        guard let mediaCacheUrl = fileManager.containerURL(forSecurityApplicationGroupIdentifier: "group.com.yourGroupHere")?.appendingPathComponent("media_cache", isDirectory: true) else { return }

        // Check to see if the directory exists. If it doesn't, we have nothing to do here.
        var isDirectory: ObjCBool = false
        let directoryExists = FileManager.default.fileExists(atPath: mediaCacheUrl.path, isDirectory: &isDirectory)
        guard directoryExists && isDirectory.boolValue else {
            print("No media_cache directory to delete.", terminator: "\n")
            return
        }

        // The directory exists and there aren't any notifications using media stored there,
        // so go ahead and delete it. Use a lock to make sure that there isn't data corruption,
        // since the directory is shared.
        let lock = NSLock()
        lock.lock()
        do {
            try FileManager.default.removeItem(at: mediaCacheUrl)
            DebugLog("Successfully deleted media_cache directory.")
        } catch let error as NSError {
            DebugLog("Error: \(error.localizedDescription). Failed to delete media_cache directory.")
        }
        lock.unlock()
    }
}

它就像一个魅力。再次感谢您为我指明正确的方向 manishsharma93。

于 2019-04-03T16:03:37.193 回答