UNNotificationAttachment无法附加图像

as *_*diu 4 ios swift usernotifications

因此,以下代码用于从图像的本地存储URL附加图像。我检查Terminal一下是否存储了图像,并且确实存储了图像,没有任何问题。因此,排除url本身的任何问题。

do {
let attachment = try UNNotificationAttachment(identifier: imageTag, url: url, options: nil)
content.attachments = [attachment]
} catch {
print("The attachment was not loaded.")
}
Run Code Online (Sandbox Code Playgroud)

创建UserNotification时附带的其他代码可以正常工作,因为它会在正确的指定时间触发。

代码总是转到catch块。如果实现中有任何人可以请我指出错误。请帮忙。谢谢。

编辑:print(error.localizedDescription)错误消息为Invalid attachment file URL

Edit2:print(error)错误消息为Error Domain=UNErrorDomain Code=100 "Invalid attachment file URL" UserInfo={NSLocalizedDescription=Invalid attachment file URL}

小智 7

我发现了背后的真正问题。在Apple文档中,该URL应该是文件URL,因此您可能会遇到问题。

为了解决这个问题,我已经将图像添加到临时目录,然后添加到UNNotificationAttachment

请在下面找到代码。[就我而言,我正在获取图片网址]

 extension UNNotificationAttachment {

/// Save the image to disk
static func create(imageFileIdentifier: String, data: NSData, options: [NSObject : AnyObject]?) -> UNNotificationAttachment? {
    let fileManager = FileManager.default
    let tmpSubFolderName = ProcessInfo.processInfo.globallyUniqueString
    let tmpSubFolderURL = NSURL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(tmpSubFolderName, isDirectory: true)

    do {
        try fileManager.createDirectory(at: tmpSubFolderURL!, withIntermediateDirectories: true, attributes: nil)
        let fileURL = tmpSubFolderURL?.appendingPathComponent(imageFileIdentifier)
        try data.write(to: fileURL!, options: [])
        let imageAttachment = try UNNotificationAttachment.init(identifier: imageFileIdentifier, url: fileURL!, options: options)
        return imageAttachment
    } catch let error {
        print("error \(error)")
    }
    return nil
}}
Run Code Online (Sandbox Code Playgroud)

此函数的参数中的data是image的数据。以下是我如何调用此方法。

let imageData = NSData(contentsOf: url)
guard let attachment = UNNotificationAttachment.create(imageFileIdentifier: "img.jpeg", data: imageData!, options: nil) else { return  }
        bestAttemptContent?.attachments = [attachment]
Run Code Online (Sandbox Code Playgroud)


Voj*_*jta 6

我还发现了UNNotificationAttachment对象初始化的重要且非常怪异的行为。我正在发生错误:

"Invalid attachment file URL"
Run Code Online (Sandbox Code Playgroud)

但这并不总是发生。当我为某些通知使用相同的附件图像时,发生了这种情况。当我为每个附件制作映像的独立副本时,它从未发生过。然后我检查了应该复制图像的目录(因为我想清理它),但是我很惊讶没有图像。

看来UNNotificationAttachment初始化过程正在删除给定URL上的文件。因此,当您尝试重用某些图像时,可以将其删除(可能是异步的,因为我正在检查这些图像的存在,并且始终使我返回true-该文件存在)。但是UNNotificationAttachment最终出现错误,您可以在上面看到。在我看来,对此错误的唯一逻辑解释是,在UNNotificationAttachment初始化过程中,删除了给定URL的文件。

  • 这应该是公认的答案,很好地解决了这种疯狂@vojta! (2认同)
  • 是的,这肯定是一种无证行为。这也是我所面临的。这很遗憾,但却是事实。“ UNNotificationAttachment 初始化过程正在删除给定 URL 处的文件”!!!!!!! (2认同)
  • 我也有这个问题。就我而言,缓存的图像文件不包含文件扩展名(如“.png”),这会导致错误。 (2认同)