本文介绍了带有Xcode,Swift3的iOS Rich Push通知,但无法获取图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Xcode,Swift3创建iOS Rich Push通知.我已经确定使用php curl命令的推送通知(主题,主体),但是我无法创建引用在本文档中.

I am trying to create iOS Rich Push notifications with Xcode, Swift3.I already make sure about push notifications (subject, body) with curl command of php but I can't create Rich Push Notifications referred to in this document.

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

I added Notification Service Extension like this: 「 File 」→「 New 」→「 Target... 」→「 Notification Service Extension 」 and also I added in 「'mutable_content': True」 curl command.

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

Then run but not call 「class NotificationService: UNNotificationServiceExtension」 so can't view push notifications image.

以下我的代码

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

推荐答案

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

我这样做是希望能对 GIF 图片有​​所帮助,您可以将扩展名更改为 .png .

I have done like this hope it helps for GIF images you can change extension to .png.

  1. 确保在APNS中,有效载荷attachment-url即将用于图像.
  2. 如果图像网址从http://...
  3. 开始,请检查应用传输安全性密钥
  4. 您的图片应在〜200px 以下.对我来说,它超出了(HIT和TRIAL)的范围.
  1. Make sure that in APNS payload attachment-url is coming for image.
  2. Check for App transport security key in case of image url start from http://...
  3. Your image should be under ~200px. For me it not works beyond(HIT and 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
    }
}

这篇关于带有Xcode,Swift3的iOS Rich Push通知,但无法获取图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 15:15