I'm working on a Flutter app and trying to display push notifications with images on iOS devices. While the notifications are received, the image does not appear. I have set up the Notification Service Extension and configured Firebase Messaging, but the image is still not displayed in the notifications.
What I've Tried:
Despite these efforts, the image still does not appear in the notifications.
Open your iOS project in Xcode (ios/Runner.xcworkspace).
Add a Target: • Go to File > New > Target. • Select Notification Service Extension and click Next. • Name it (e.g., NotificationService) and click Finish.
Update the Deployment Target to match the main app (e.g., iOS 15.5).
 import UserNotifications
 import UIKit
 class NotificationService: UNNotificationServiceExtension {
 override func didReceive(_ request: UNNotificationRequest, 
 withContentHandler contentHandler: @escaping (UNNotificationContent) 
 -> Void) {
 guard let bestAttemptContent = (request.content.mutableCopy() as? 
 UNMutableNotificationContent) else {
 return contentHandler(request.content)
 }
 if let imageURLString = request.content.userInfo["media-url"] as? 
 String,
 let imageURL = URL(string: imageURLString) {
 downloadImage(from: imageURL) { imageAttachment in
  if let attachment = imageAttachment {
      bestAttemptContent.attachments = [attachment]
 }
 contentHandler(bestAttemptContent)
 }
 } else {
 contentHandler(bestAttemptContent)
 }
 }
private func downloadImage(from url: URL, completion: @escaping 
(UNNotificationAttachment?) -> Void) {
let task = URLSession.shared.downloadTask(with: url) { 
(downloadedURL, _, _) in
guard let downloadedURL = downloadedURL else {
return completion(nil)
}
do {
let attachment = try UNNotificationAttachment(identifier: 
url.lastPathComponent,
url: downloadedURL,options: nil)
completion(attachment)
} catch {
completion(nil)
}
}
task.resume()
}
}
Send Basic Notification Payload
         {
         "to": "<device_token>",
         "notification": {
         "title": "Notification Title",
         "body": "Notification Body"
          },
         "data": {
         "media-url": "https://example.com/image.jpg"
         }
         }
Flutter code receive notification:
        FirebaseMessaging.onMessage.listen((RemoteMessage message) {
        if (message.data.containsKey('media-url')) {
        String imageUrl = message.data['media-url']!;
        showDialog(
        context: context,
        builder: (context) => AlertDialog(
        title: Text(message.notification?.title ?? 'Notification'),
        content: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
        Text(message.notification?.body ?? ''),
        Image.network(imageUrl),
        ],
        ),
        ),
        );
        }
        });
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With