Входящие насыщенные push-уведомления не будут отображать изображение.Swift 4 - PullRequest
1 голос
/ 12 июня 2019

Я пытаюсь реализовать расширенные push-уведомления, но я не получаю изображение с переданным URL для отображения.Когда я открываю уведомление, я вижу только заголовок, подзаголовок и текст.Я следую учебному пособию на https://www.pluralsight.com/guides/creating-ios-rich-push-notifications, как я нашел в других постах, но я застрял при показе изображения.Я также прочитал в одном посте, что я не должен запускать приложение, но NotificationExtension, но когда я это делаю, приложение вылетает при получении уведомления с

Сообщение от отладчика: прекращено из-за сигнала 9 Программазакончилась с кодом выхода: 0

сообщение.

Это печать userInfo при запуске приложения вместо:

[AnyHashable ("attachment-url"): https://firebasestorage.googleapis.com/v0/b/fix-it-b4b00.appspot.com/o/Prodotti%2FPrato.jpeg?alt=media&token=5d0fde09-2b86-45b0-a383-a11e7e8e241c, AnyHashable ("gcm.message_id "): 1560360808567562, AnyHashable (" productId "): 9290CEBE-393C-4285-BE7B-B9E2968A1AA0, AnyHashable (" aps "): {alert = {body =" Nuova promozione per articolo: Prato ";subtitle = "Negozio: Vincenzo Calia";title = "Promozione negozio";};«контент-доступный» = 1;"mutable-content" = 1;звук = правда;}, AnyHashable ("price"): 10.00, AnyHashable ("gcm.notification.priority"): high, AnyHashable ("google.cae"): 1]

Я проверил, и URL-адресправильный.Может быть проблема в том, что URL не в строковом формате?Я поставил отпечаток, чтобы проверить это, но я даже не получаю печать в начале метода didReceive.Вы видите, где возможно что-то идет не так?Как всегда Большое спасибо за ваш интерес и время.

Это функция в NotificationService.swift:

override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {

        print("NotificationService: dide receive called")
        self.contentHandler = contentHandler
        bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)

        func failEarly() {
            contentHandler(request.content)
        }

        guard let content = (request.content.mutableCopy() as? UNMutableNotificationContent) else {
            return failEarly()
        }

        guard let apnsData = content.userInfo["data"] as? [String: Any] else {
            return failEarly()
        }

        guard let attachmentURL = apnsData["attachment-url"] as? String else {
            print("url is not in string form")
            return failEarly()
        }

        guard let imageData = NSData(contentsOf:NSURL(string: attachmentURL)! as URL) else { return failEarly() }
        guard let attachment = UNNotificationAttachment.create(imageFileIdentifier: "image.gif", data: imageData, options: nil) else { return failEarly() }

        content.attachments = [attachment]
        contentHandler(content.copy() as! UNNotificationContent)
    }

    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: NSData, options: [NSObject : AnyObject]?) -> UNNotificationAttachment? {

        let fileManager = FileManager.default
        let tmpSubFolderName = ProcessInfo.processInfo.globallyUniqueString
        let fileURLPath      = NSURL(fileURLWithPath: NSTemporaryDirectory())
        let tmpSubFolderURL  = fileURLPath.appendingPathComponent(tmpSubFolderName, isDirectory: true)

        do {
            try fileManager.createDirectory(at: tmpSubFolderURL!, withIntermediateDirectories: true, attributes: nil)
            let fileURL = tmpSubFolderURL?.appendingPathComponent(imageFileIdentifier)
            try data.write(to: fileURL!, options: [])
            let imageAttachment = try UNNotificationAttachment.init(identifier: imageFileIdentifier, url: fileURL!, options: options)
            return imageAttachment
        } catch let error {
            print("error \(error)")
        }

        return nil
    }
}

И эта функция отправляет push-уведомление:

static func sendTopicPushNotification(to topic: String, title: String, subtitle: String, body: String, dataUrl: String, productId: String, price: String) {
        let serverKey = firebaseServerKey // AAAA8c3j2...
        //            let topic = "/topics/<your topic here>"  // replace it with partnerToken if you want to send a topic
        let url = NSURL(string: "https://fcm.googleapis.com/fcm/send")

        let postParams: [String : Any] = [
            "to": topic,
//            "priority": "high",
//            "content_available": true,
//            "mutable_content": true,
            "notification": [
                //                    "badge" : 1, sendig the badge number, will cause aglitch
                "body": body,
                "title": title,
                "subtitle": subtitle,
                "text": "some text",
                "sound" : true, // or specify audio name to play
                "priority": "high",
                "content_available": true,
                "mutable_content": true
//                 "category" : "pushNotificationCategory" // "topicPushNotification"
//                    "click_action" : "?", // action when user click notification (categoryIdentifier)
            ],
            "data" : [
                "attachment-url": dataUrl,
                "productId": productId,
                "price": price
            ]
        ]


        let request = NSMutableURLRequest(url: url! as URL)
       request.httpMethod = "POST"
        request.setValue("key=\(serverKey)", forHTTPHeaderField: "Authorization")
        request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")

        do {
            //                request.httpBody = try JSONSerialization.data(withJSONObject: postParams, options: JSONSerialization.WritingOptions())
            request.httpBody = try JSONSerialization.data(withJSONObject: postParams, options: [.prettyPrinted]) // working
            print("sendTopicPushNotification : My paramaters: \(postParams)")
        } catch {
            print("sendTopicPushNotification : Caught an error: \(error)")
        }

        let task = URLSession.shared.dataTask(with: request as URLRequest) { (data, response, error) in
            if let realResponse = response as? HTTPURLResponse {
                if realResponse.statusCode != 200 {
                    print("sendTopicPushNotification : Not a 200 response : \(realResponse)")
                }
                print("sendTopicPushNotification : response : \(realResponse)")
            }

            if let postString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue) as String? {
                print("sendTopicPushNotification : POST: \(postString)")
            }
        }

        task.resume()
    }

1 Ответ

0 голосов
/ 13 июня 2019

Я наконец-то смог показать картинку с уведомлением.Это может быть связано с тем, что учебник, которому я следую, предназначен для swift 5, а я на swift 4. Я изменил код didReceive и пропустил код extension UNNotificationAttachment, и теперь он отображается правильно.Следующим шагом является добавление действий на основе категории, полученной в полезной нагрузке, но я все еще должен выяснить, возможно ли это без реализации также расширения содержимого уведомлений, которое, как я понял, должно состоять только в том, чтобы иметь собственное представление для отображенияуведомление.Любой намек будет очень признателен.Я надеюсь, что это поможет другим, так как учебники, которые я нашел по этому вопросу, иногда сбивают с толку и вводят в заблуждение.Также большое спасибо за то, что проголосовали за вопрос.

NotificationServiceExtension didReceive теперь:

override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) {

        print("NotificationService: dide receive called")
        self.contentHandler = contentHandler
        bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent)

        if let bestAttemptContent = bestAttemptContent {
            if let urlString = bestAttemptContent.userInfo["attachment-url"] as? String,
                let data = NSData(contentsOf: URL(string:urlString)!) as Data? {
                let path = NSTemporaryDirectory() + "attachment"
                _ = FileManager.default.createFile(atPath: path, contents: data, attributes: nil)

                do {
                    let file = URL(fileURLWithPath: path)
                    let attachment = try UNNotificationAttachment(identifier: "attachment", url: file,options:[UNNotificationAttachmentOptionsTypeHintKey : "public.jpeg"])
                    bestAttemptContent.attachments = [attachment]

                } catch {
                    print(error)

                }
            }

            contentHandler(bestAttemptContent)
        }
...