flutter 抖动图像通知

y3bcpkx1  于 2023-05-08  发布在  Flutter
关注(0)|答案(1)|浏览(176)

抖动图像通知不能在后台工作&终止。它在前台正常工作。下载一个图像并保存临时目录(Directory.systemTemp),然后获取一个在前台显示图像的路径

`if (Platform.isIOS) {
    if (message.data['image'] != null) {
      url = message.data['image'];
      var formatname = url.toString().split(".");
      var length = formatname.length - 1;
      var format = formatname[length];
      log("message$format");
      var formatlist = ['jpg', 'gif', 'png'];
      bigpicture = await DownloadUtil.downloadfiles(url,
          "bigpicture.${(format.isEmpty || formatlist.contains(format)) ? format : "jpg"}");
      print(bigpicture);
    } else {
      bigpicture = " ";
    }
  } 
}`

flutter本地通知插件版本(flutter_local_notifications:^9.2.0). firebase消息传递包版本(firebase消息传递:^11.2.5).

`flutterLocalNotificationsPlugin.show(
        id,
        message.data["title"],
        message.data["body"],
        NotificationDetails(
          iOS: ios != null
              ? IOSNotificationDetails(
                  attachments: message.data['image'] != null
                      ? <IOSNotificationAttachment>[
                          IOSNotificationAttachment(bigpicture),
                        ]
                      : <IOSNotificationAttachment>[],
                )
              : null,
        ),
        payload: json.encode(message.data));`

有效载荷:-

`{
    "message": {
        "notification": {
            "title": "Welcome message",
            "body": "Firebase Nodification Success",
            "sound": "Default",
            "imageUrl": "https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__480.jpg"
        },
        "data": {
            "title": "Welcome message12",
            "body": "Firebase Nodification Success🙂",
            "click_action": "FLUTTER_NOTIFICATION_CLICK",
            "image": "https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__480.jpg",
            "status": "Received"
        }
    },
    "registrationToken": "**fcmtoken**"
}`

Flutter医生:-

`Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 2.10.5, on macOS 12.5.1 21G83 darwin-arm, locale en-IN)
[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
[✓] Xcode - develop for iOS and macOS (Xcode 13.4)
[✓] Chrome - develop for the web
[✓] Android Studio (version 2021.2)
[✓] VS Code (version 1.69.2)
[✓] Connected device (2 available

[✓] HTTP Host Availability
• No issues found!`
4uqofj5v

4uqofj5v1#

payload:-

{
 "notification": {
     "title": "New image",
     "body": "Check out this cool image!"
 },
 "data": {
     "title": "Example Notification001",
     "body": "Check out this cool image!:slightly_smiling_face:",
     "click_action": "FLUTTER_NOTIFICATION_CLICK",
     "image": "https://img.freepik.com/free-photo/chicken-wings-barbecue-sweetly-sour-sauce-picnic-summer-menu-tasty-food-top-view-flat-lay_2829-6471.jpg"
 },
 "apns": {
     "payload": {
         "aps": {
             "mutable-content": 1,
             "sound": "Default"
         }
     }
 },
 "registrationToken": [
     "**Your fcm token**"
 ]
}

创建通知服务扩展

成功创建iOS应用程序后,您需要创建通知服务扩展。以下是如何创建通知服务扩展的步骤。
1.在Xcode菜单中,转到File > New > Target。
1.选择Notification Service Extension。
1.给出扩展服务的名称并单击完成按钮。

根据您的意愿键入产品名称(例如:-ImageNotificationService)
您在xcode中添加了firebase Messaging包(此行是在您的包中安装firebase messaging)(target 'this your notification service contact name'

target 'ImageNotificationService' do
  use_frameworks!
  pod 'Firebase/Messaging'
end

此Info.plist在imagenotificationservice文件夹plist中

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>NSExtension</key>
    <dict>
        <key>UNNotificationExtensionCategory</key>
        <string>imageNotificationCategory</string>
        <key>NSExtensionAttributes</key>
        <dict>
            <key>UNNotificationExtensionDefaultContentHidden</key>
            <false/>
            <key>UNNotificationExtensionInitialContentSizeRatio</key>
            <real>1</real>
        </dict>
        <key>NSExtensionPointIdentifier</key>
        <string>com.apple.usernotifications.service</string>
        <key>NSExtensionPrincipalClass</key>
        <string>$(PRODUCT_MODULE_NAME).NotificationService</string>
    </dict>
</dict>
</plist>

此行为notificationservice.swift

import UIKit
import UserNotifications
import FirebaseMessaging

class NotificationService: UNNotificationServiceExtension {

    var contentHandler: ((UNNotificationContent) -> Void)?
    var bestAttemptContent: UNMutableNotificationContent?

    override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {
        self.contentHandler = contentHandler
        bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)
        guard let bestAttemptContent = bestAttemptContent else { return }
        // Modify the notification content here as you wish
        let data = bestAttemptContent.userInfo as NSDictionary
        let pref = UserDefaults.init(suiteName: "group.id.gits.notifserviceextension")
        pref?.set(data, forKey: "NOTIF_DATA")
        pref?.synchronize()
        NSLog("notificationserviceExtension")
        guard let attachmentURL = data["image"] as? String else {
                    contentHandler(bestAttemptContent)
                    return
                }
        do {
             print("unNotification sucesss01---\(attachmentURL)")
            let imageData = try Data(contentsOf: URL(string: attachmentURL)!)
            guard let attachment = UNNotificationAttachment.create(imageFileIdentifier: "image.jpg", data: imageData, options: nil) else {
                contentHandler(bestAttemptContent)
                return
            }
            bestAttemptContent.attachments = [attachment]
            contentHandler(bestAttemptContent.copy() as! UNNotificationContent)
            
        } catch {
            self.bestAttemptContent?.title = "\(self.bestAttemptContent?.title ?? "")."
            self.bestAttemptContent?.body = "\(self.bestAttemptContent?.body ?? "")"
            contentHandler(bestAttemptContent)
            print("Unable to load data: \(error)")

        }
    }
    
    override func serviceExtensionTimeWillExpire() {
        // Called just before the extension will be terminated by the system.
        // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used.
        if let contentHandler = contentHandler, let bestAttemptContent =  bestAttemptContent {
            contentHandler(bestAttemptContent)
        }
    }

}
extension UNNotificationAttachment {
    static func create(imageFileIdentifier: String, data: Data, options: [NSObject: AnyObject]?) -> UNNotificationAttachment? {
        let fileManager = FileManager.default
        let tmpSubFolderName = ProcessInfo.processInfo.globallyUniqueString
        let tmpSubFolderURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(tmpSubFolderName, isDirectory: true)

        do {
            try fileManager.createDirectory(at: tmpSubFolderURL, withIntermediateDirectories: true, attributes: nil)
            let fileURL = tmpSubFolderURL.appendingPathComponent(imageFileIdentifier)
            try data.write(to: fileURL)
            let attachment = try UNNotificationAttachment(identifier: imageFileIdentifier, url: fileURL, options: options)
            return attachment
        } catch {
            print("Error creating attachment: \(error)")
        }
        return nil
    }
}

如果您有任何疑问,请在下面评论:-

相关问题