ios - 将缩略图附加到通知时,文件去了哪里?

标签 ios swift notifications uilocalnotification unnotificationattachment

我正在向富通知添加缩略图。我生成用作附件的图像,如下所示:

let url = URL(fileURLWithPath: NSTemporaryDirectory(), isDirectory: true)
let fileURL = url.appendingPathComponent("someImageName", isDirectory: false).appendingPathExtension("png")
do{
    try UIImagePNGRepresentation(image)?.write(to: fileURL)
}catch{
    print("Could not write: ", error)
}

这是成功的。如果我现在运行这段代码:

let content = try? FileManager.default.contentsOfDirectory(atPath: NSTemporaryDirectory())
print(content ?? "error")

它打印出这个:["someImageName.png"]

然后我创建附件,如下所示:

let attachment = try? UNNotificationAttachment(identifier: "image", url: url, options: nil)
let content = UNMutableNotificationContent()
content.title = "Test"
content.attachments = [attachment!]
let request = UNNotificationRequest(identifier: "someID", content:content, trigger: /*someTrigger*/)
UNUserNotificationCenter.current().add(request, withCompletionHandler:...)

一切正常。通知已发送,并附上附件。但是如果我现在打印出临时文件夹的内容,它是空的!我之前保存的图像已从此文件夹中删除。

经过反复试验,我发现在我添加通知的同时删除了图像。为什么我的通知会删除我的图片?我找不到这方面的任何文档!

如果我执行以上所有操作,但注释掉这一行://content.attachments = [attachment!],这意味着我存储的图像将不会作为附件添加到我的通知中,然后我的图片没有从临时文件夹中删除!

这些文件在使用后是否被清理?或者我是否必须在通知消失后查看不同的文件夹并手动清理它们?我不希望我的应用程序创建数百张永远不会再使用的图像,而且无法删除它们。

最佳答案

这些天我遇到了同样的问题,答案在文档中,乍一看不是很容易看到,但它就在那里:

关于UNNotificationAttachment:

...Once validated, attached files are moved into the attachment data store so that they can be accessed by all of the appropriate processes.

关于初始化方法:

When you schedule a notification request containing the attachment, the attachment's file is moved to a new location to facilitate access by the appropriate processes. After the move, the only way to access the file is using the methods of the UNUserNotificationCenter object.

注意:

Attachments located inside an app's bundle are copied instead of moved.

所以我决定:

像你一样写文件并在 NSTemporaryDirectory() 中写一个副本我用这个例子轻松创建和删除 TempDirectory (Swift 4.0)(感谢 Ole Begemman ):

import Foundation

/// A wrapper around a temporary file in a temporary directory. The directory
/// has been especially created for the file, so it's safe to delete when you're
/// done working with the file.
///
/// Call `deleteDirectory` when you no longer need the file.
struct TemporaryFile {
    let directoryURL: URL
    let fileURL: URL
    /// Deletes the temporary directory and all files in it.
    let deleteDirectory: () throws -> Void
    
    /// Creates a temporary directory with a unique name and initializes the
    /// receiver with a `fileURL` representing a file named `filename` in that
    /// directory.
    ///
    /// - Note: This doesn't create the file!
    init(creatingTempDirectoryForFilename filename: String) throws {
        let (directory, deleteDirectory) = try FileManager.default
            .urlForUniqueTemporaryDirectory()
        self.directoryURL = directory
        self.fileURL = directory.appendingPathComponent(filename)
        self.deleteDirectory = deleteDirectory
    }
}

extension FileManager {
    /// Creates a temporary directory with a unique name and returns its URL.
    ///
    /// - Returns: A tuple of the directory's URL and a delete function.
    ///   Call the function to delete the directory after you're done with it.
    ///
    /// - Note: You should not rely on the existence of the temporary directory
    ///   after the app is exited.
    func urlForUniqueTemporaryDirectory(preferredName: String? = nil) throws
        -> (url: URL, deleteDirectory: () throws -> Void)
    {
        let basename = preferredName ?? UUID().uuidString
        
        var counter = 0
        var createdSubdirectory: URL? = nil
        repeat {
            do {
                let subdirName = counter == 0 ? basename : "\(basename)-\(counter)"
                let subdirectory = temporaryDirectory
                    .appendingPathComponent(subdirName, isDirectory: true)
                try createDirectory(at: subdirectory, withIntermediateDirectories: false)
                createdSubdirectory = subdirectory
            } catch CocoaError.fileWriteFileExists {
                // Catch file exists error and try again with another name.
                // Other errors propagate to the caller.
                counter += 1
            }
        } while createdSubdirectory == nil
        
        let directory = createdSubdirectory!
        let deleteDirectory: () throws -> Void = {
            try self.removeItem(at: directory)
        }
        return (directory, deleteDirectory)
    }
}

使用 TempURL 附加文件后,文件被移动,您可以删除 TempDirectory。

后来进行了一些测试,可以肯定的是,我终于发现我的文件(在我的案例中是一张图片)存储在这里:

URL: file:///var/mobile/Library/SpringBoard/PushStore/Attachments/com.YourApp.Name/8e52c6673f6e735f83535486bf750ba1118a3ade.png

提示或清理通知中心后,文件被删除是。

为什么会这样? -> 沙盒!当我将我的文件附加到触发器(此处为 UNCalendarNotificationTrigger)时,我将负责我的文件的日历命名为在我的通知中显示它,但要处理它,它必须将文件放在 HIS 目录中。

希望对您有所帮助,我花了一段时间才找到所有的谜团!

关于ios - 将缩略图附加到通知时,文件去了哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44921965/

相关文章:

ios - 应用程序未重新创建 iCloud Drive 文件夹

ios - EXC_BAD_ACCESS KERN_PROTECTION_FAILURE 32位设备崩溃

windows-phone-8 - Windows Phone 8 中的本地 toast 通知

android - Parse.com 无法将通知推送到多个设备 android

objective-c - 如何在我的 AppDelegate 中设置一个引用已初始化的 Storyboard ViewController 的变量

ios - 如何从设备中的图像读取二维码

ios - PhoneGap iOS-media.startRecord文件URI不起作用

iphone - 我的应用程序需要时间进行初始启动

ios - 从 NSManagedObject 中的 for 循环获取索引

iphone - 处理在应用程序未运行时触发但在应用程序运行时仍显示的通知警报