检索 UNNotificationAttachment 时 UIImage 未完全加载

UIImage not fully loaded when retrieving UNNotificationAttachment

我有一个 NotificationContentExtension 并且想在 UIImageView 中显示 NotificationAttachment。效果很好,但是当我扩展推送通知(因此 NotificationContentExtension 加载)时,图像似乎没有完全加载。它的右下角有一个灰色矩形,当我用 NotificationServiceExtension 显示它时它不存在。

这是我的 NotificationContentExtension 中的 didReceive 方法:

func didReceive(_ notification: UNNotification) {
    let content = notification.request.content;
    
    self.name.text = content.title
    self.subject.text = content.subtitle
    self.body.text = content.body
    
    if let attachment = content.attachments.first {
         if attachment.url.startAccessingSecurityScopedResource() {
            self.profilePicture.image = UIImage(contentsOfFile: attachment.url.path)
            attachment.url.stopAccessingSecurityScopedResource()
         }
    }
}

我是不是做错了什么?

问题是在 UIImage 完全加载之前停止了对资源的访问。使用 DispatchQueue 并使用 imageData 加载 UIImage 为我解决了这个问题。

func didReceive(_ notification: UNNotification) {
    self.name.text = notification.request.content.title
    self.subject.text = notification.request.content.subtitle
    self.body.text = notification.request.content.body
    
    let imageUrl: URL? = notification.request.content.attachments.first!.url
    
    if let url = imageUrl, url.startAccessingSecurityScopedResource() {
        DispatchQueue.global().async {
            var imageData: Data?
            do {
                imageData = try Data(contentsOf: url)
            } catch let error {
                print(error);
            }
            DispatchQueue.main.async {
                self.profilePicture.image = UIImage(data: imageData!)
                url.stopAccessingSecurityScopedResource()
            }
        }
    }
}