1

我有一个 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()
         }
    }
}

难道我做错了什么?

4

1 回答 1

1

问题是对资源的访问在 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()
            }
        }
    }
}
于 2021-05-07T09:04:01.167 回答