当前位置 : 主页 > 手机开发 > ios >

ios – UNNotificationAttachment无法附加图像

来源:互联网 收集:自由互联 发布时间:2021-06-11
因此,以下代码用于附加图像的本地存储URL中的图像.我检查终端,看看图像是否存储,它确实存储图像没有任何问题.所以排除网址本身的任何问题. do {let attachment = try UNNotificationAttachment(
因此,以下代码用于附加图像的本地存储URL中的图像.我检查终端,看看图像是否存储,它确实存储图像没有任何问题.所以排除网址本身的任何问题.

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

与UserNotification创建一起使用的其他代码在正确的指定时间触发时工作正常.

代码总是进入catch块.任何人都可以指出我的错误,如果有任何实施.请帮忙.谢谢.

编辑:带打印(error.localizedDescription)错误消息是无效的附件文件URL.

Edit2:带打印(错误)错误消息是错误域= UNErrorDomain代码= 100“无效的附件文件URL”UserInfo = {NSLocalizedDescription =无效的附件文件URL}

我发现了背后的真正问题.在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
}}

此函数的参数中的数据是图像数据.以下是我如何称呼这种方法.

let imageData = NSData(contentsOf: url)
guard let attachment = UNNotificationAttachment.create(imageFileIdentifier: "img.jpeg", data: imageData!, options: nil) else { return  }
        bestAttemptContent?.attachments = [attachment]
网友评论