iosswiftapple-push-notificationsunnotificationattachmentunnotificationscontentextension

UIImage not fully loaded when retrieving UNNotificationAttachment


I have a NotificationContentExtension and want to display the NotificationAttachment in a UIImageView. That works fine but when I extend the push notification (so the NotificationContentExtension loads) it seems like the image is not fully loaded. It has a grey rectangle in the bottom right corner which was not there when I displayed it with the NotificationServiceExtension.

This is the didReceive method in my NotificationContentExtension:

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()
         }
    }
}

Am I doing something wrong?


Solution

  • The issue was that the access to the resource got stopped before the UIImage was fully loaded. Using DispatchQueue and loading the UIImage with imageData solved this for me.

    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()
                }
            }
        }
    }