【问题标题】:iOS Rich Push notifications with Xcode, Swift3 but cannot get image带有Xcode,Swift3的iOS Rich Push通知但无法获取图像
【发布时间】:2018-07-30 15:57:14
【问题描述】:

我正在尝试使用 Xcode、Swift3 创建 iOS 富推送通知。 我已经使用 php 的 curl 命令确定了推送通知(主题、正文),但我无法创建引用 in this document 的丰富推送通知。

我添加了这样的通知服务扩展:「 File 」→「 New 」→「 Target... 」→「 Notification Service Extension 」,并且我还添加了「'mutable_content': True」 curl 命令。

然后运行但不调用「class NotificationService: UNNotificationServiceExtension」,因此无法查看推送通知图像。

下面是我的代码

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)
        }
    }
}

【问题讨论】:

    标签: ios xcode swift3 unnotificationserviceextension rich-notifications


    【解决方案1】:

    参考https://www.pluralsight.com/guides/swift/creating-ios-rich-push-notifications

    我已经这样做了,希望它对 GIF 图片有所帮助,您可以将扩展名更改为 .png

    1. 确保在 APNS 有效负载中 attachment-url 用于图像。
    2. 检查 App transport security 密钥以防图像 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
        }
    }
    

    【讨论】:

    • 真的非常感谢您为我的问题发帖。我在这里提出了一个问题link 结果我无法获得图像...如果您有任何想法,请再次回答非常感谢。 @Abhishek Thapliyal
    • 你只需调整图像大小你会得到图像 100*100px
    • 非常感谢您回复@Abhishek Thapliyal。立即尝试调整图像大小但仍然无效...首先不要运行「class NotificationService: UNNotificationServiceExtension」有什么想法吗??再次抱歉,非常感谢您。
    • 你能检查 url 是否正确,如果 HTTP 则 app trnas 端口安全问题?
    猜你喜欢
    • 2018-07-31
    • 1970-01-01
    • 2020-04-19
    • 2018-10-30
    • 1970-01-01
    • 1970-01-01
    • 2021-02-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多