Flutter: Как отобразить расширенные уведомления на ios с помощью плагина flutter_messaging? - PullRequest
0 голосов
/ 04 апреля 2020

Одной из проблем с firebase_messaging является невозможность отображения уведомлений с изображениями на ios. Я пытаюсь реализовать собственный способ отображения мультимедиа, но безрезультатно. Мне не хватает ios знаний, чтобы на самом деле понять, что происходит, и почему они не отображаются в текущей реализации. В настоящее время получает только текстовые уведомления pu sh от консоли FCM и почтальона, если объект уведомления включен.

NotificationService

   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)

        defer {
            contentHandler(bestAttemptContent ?? request.content)
        }

        guard let attachment = request.attachment else { return }

        bestAttemptContent?.attachments = [attachment]
    }

    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 UNNotificationRequest {
    var attachment: UNNotificationAttachment? {
        guard let attachmentURL = content.userInfo["image_url"] as? String, let imageData = try? Data(contentsOf: URL(string: attachmentURL)!) else {
            return nil
        }
        return try? UNNotificationAttachment(data: imageData, options: nil)
    }
}

extension UNNotificationAttachment {

    convenience init(data: Data, options: [NSObject: AnyObject]?) throws {
        let fileManager = FileManager.default
        let temporaryFolderName = ProcessInfo.processInfo.globallyUniqueString
        let temporaryFolderURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(temporaryFolderName, isDirectory: true)

        try fileManager.createDirectory(at: temporaryFolderURL, withIntermediateDirectories: true, attributes: nil)
        let imageFileIdentifier = UUID().uuidString + ".jpg"
        let fileURL = temporaryFolderURL.appendingPathComponent(imageFileIdentifier)
        try data.write(to: fileURL)
        try self.init(identifier: imageFileIdentifier, url: fileURL, options: options)
    }
}

AppDelegate

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {

  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?
  ) -> Bool {
    GeneratedPluginRegistrant.register(with: self)
    if #available(iOS 10.0, *) {
      UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
    }
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}

Полезная нагрузка отправлено почтальоном

{
    "to": "/topics/red",
    "content_available": true,
    "mutable_content": true,
    "notification": {
        "badge": 9,
        "title": "awd4",
        "mutable-content": true,
        "body": "bod",
        "image_url": "https://www.imgonline.com.ua/examples/jpeg-quality-10.jpg"
    },
    "image_url": "https://www.imgonline.com.ua/examples/jpeg-quality-10.jpg",
    "priority": "high"
}

Возможно ли это вообще, все еще получая обратные вызовы в сторону дротика, или единственный способ - полностью встроенная интеграция FCM с каналами платформы?

1 Ответ

0 голосов
/ 04 апреля 2020

Изменено содержимое - доступно с true на false, и это сработало. Кредиты на u / imtoori от Reddit.

...