iOS Rich Push-уведомления с Xcode, Swift3, но не может получить изображение

Я пытаюсь создать iOS Rich Push-уведомления с помощью Xcode, Swift3. Я уже знаю о push-уведомлениях (тема, тело) с помощью команды curl в php, но не могу создать расширенные push-уведомления со ссылкой на в этом документе.

Я добавил расширение службы уведомлений следующим образом: 「 File 」→「 New 」→「 Target... 」→「 Notification Service Extension 」, а также добавил команду 「'mutable_content': True」 curl.

Затем запустите, но не вызывайте 「class NotificationService: UNNotificationServiceExtension」, чтобы не было возможности просматривать изображение push-уведомлений.

Следующий мой код

import UserNotifications 
class NotificationService: UNNotificationServiceExtension {

    let imageKey = AnyHashable("gcm.notification.image_url")

    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)

        if let imageUrl = request.content.userInfo[imageKey] as? String {
            let session = URLSession(configuration: URLSessionConfiguration.default)
            let task = session.dataTask(with: URL(string: imageUrl)!, completionHandler: { [weak self] (data, response, error) in
                if let data = data {
                    do {
                        let writePath = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("push.png")
                        try data.write(to: writePath)
                        guard let wself = self else {
                            return
                        }
                        if let bestAttemptContent = wself.bestAttemptContent {
                            let attachment = try UNNotificationAttachment(identifier: "nnsnodnb_demo", url: writePath, options: nil)
                            bestAttemptContent.attachments = [attachment]
                            contentHandler(bestAttemptContent)
                        }
                    } catch let error as NSError {
                        print(error.localizedDescription)

                        guard let wself = self else {
                            return
                        }
                        if let bestAttemptContent = wself.bestAttemptContent {
                            contentHandler(bestAttemptContent)
                        }
                    }
                } else if let error = error {
                    print(error.localizedDescription)
                }
            })
            task.resume()
        } else {
            if let bestAttemptContent = bestAttemptContent {
                contentHandler(bestAttemptContent)
            }
        }
    }

    override func serviceExtensionTimeWillExpire() {
        if let contentHandler = contentHandler, let bestAttemptContent =  bestAttemptContent {
            contentHandler(bestAttemptContent)
        }
    }
}

person iwahei0813    schedule 20.02.2018    source источник


Ответы (1)


ССЫЛКА: https://www.pluralsight.com/guides/swift/creating-ios-rich-push-notifications

Я сделал так, надеюсь, что это поможет для изображений GIF, вы можете изменить расширение на .png.

  1. Убедитесь, что в полезной нагрузке APNS идет attachment-url для изображения.
  2. Проверьте ключ Безопасность транспорта приложения, если URL изображения начинается с http://....
  3. Ваше изображение должно быть меньше ~200px. Для меня это не работает дальше (HIT и TRIAL).

Код:

import UserNotifications
import SDWebImage

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)

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

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

        guard let attachmentURL = content.userInfo["attachment-url"] as? String else {
            return failEarly()
        }

        SDWebImageDownloader.shared().downloadImage(with: URL(string: attachmentURL)!,
                                                    options: SDWebImageDownloaderOptions.continueInBackground,
                                                    progress: nil) { (image, data, error, flag) in

            guard let attachment = UNNotificationAttachment.create(imageFileIdentifier: "image.gif",
                                                                    data: data! as NSData,
                                                                    options: nil) else { return failEarly() }
            content.attachments = [attachment]
            contentHandler(content.copy() as! UNNotificationContent)

            if let bestAttemptContent = self.bestAttemptContent {
                bestAttemptContent.title = "\(bestAttemptContent.title) [modified]"
                contentHandler(bestAttemptContent)
            }
        }
    }

    override func serviceExtensionTimeWillExpire() {
        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 tmpSubFolderURL = NSURL(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!, options: [])
            let imageAttachment = try UNNotificationAttachment(identifier: imageFileIdentifier, url: fileURL!, options: options)
            return imageAttachment
        } catch let error {
            print("error \(error)")
        }

        return nil
    }
}
person Abhishek Thapliyal    schedule 20.02.2018
comment
действительно очень спасибо за мой вопрос. я задал вопрос здесь ссылка как результат я не мог получить изображение ... если у вас есть какие-либо идеи, пожалуйста, ответьте еще раз большое спасибо. @Абхишек Таплиял - person iwahei0813; 22.02.2018
comment
вы просто измените размер изображения, и вы получите изображение 100 * 100 пикселей - person Abhishek Thapliyal; 22.02.2018
comment
например: humethnet.files.wordpress.com/2016/02/ - person Abhishek Thapliyal; 22.02.2018
comment
большое спасибо за ответ @Abhishek Thapliyal. Сразу попробовал изменить размер изображения, но все равно не работает... Во-первых, не запускайте 「class NotificationService: UNNotificationServiceExtension」, есть идеи?? еще раз извините и большое спасибо. - person iwahei0813; 22.02.2018
comment
можете ли вы проверить, что URL-адрес получает правильно, и если HTTP, то проблема с безопасностью порта trnas приложения? - person Abhishek Thapliyal; 22.02.2018
comment
большое спасибо за ответ @Abhishek Thapliyal. Я добавил в код NotificationService(info.plist) ‹key›NSAppTransportSecurity‹/key› ‹dict› ‹key›NSAllowsArbitraryLoads‹/key› ‹true/› ‹/dict›, тогда работает! спасибо сососососо большое! Но мне интересно, почему не выводить print(hogehogehogehoge) это спецификация или моя ошибка?? - person iwahei0813; 23.02.2018
comment
ХАХАХА: журналы расширения p в консоли - это ошибка в xcode, наслаждайтесь этими ошибками, мне также не удалось получить журналы: p: D, вы также можете поддержать мой ответ - person Abhishek Thapliyal; 23.02.2018