【问题标题】:UIImage not fully loaded when retrieving UNNotificationAttachment检索 UNNotificationAttachment 时 UIImage 未完全加载
【发布时间】:2021-07-29 13:27:47
【问题描述】:

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

我是不是做错了什么?

【问题讨论】:

    标签: ios swift apple-push-notifications unnotificationattachment unnotificationscontentextension


    【解决方案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()
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2019-05-28
      • 2020-05-21
      • 2016-12-30
      • 1970-01-01
      • 1970-01-01
      • 2011-09-19
      • 2016-06-10
      • 2010-10-06
      相关资源
      最近更新 更多