如何在iOS Notification Service Extension中删除文件?

时间:2019-03-28 22:08:25

标签: ios unnotificationserviceextension

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

  • 我尝试删除AppDelegate中的文件,但是我相信UNNotificationServiceExtension在本文档的“与包含应用程序共享数据”部分中有自己的Documents目录:{{3} },因此我无法从主应用程序访问这些文件。它们在另一个容器中。
  • 我不想创建一个App Group只是为了在App和扩展之间共享数据,以便删除未使用的文件。
  • 我不想删除UNNotificationServiceExtension中未使用的文件,因为该扩展名在有限的时间内可以完成其工作,并且如果我尝试下载文件并删除其他文件,则它会可能会超时。

我认为最好的选择是检查所有传递的通知都需要哪些文件,并删除Notification Service Extension的Documents目录中不需要的文件。我对此感到担心的是,UNNotificationServiceExtension仅在很短的时间内必须完成其所有工作,然后才会超时。

所以,我的问题是,“这是从Notification Service Extension中清除未使用的文件的正确方法,还是有更好的方法?”

1 个答案:

答案 0 :(得分: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。