我正在使用通知服务扩展程序,但我无法在通知中获取图像,如何在通知中心获取图像?

时间:2018-01-25 10:19:39

标签: ios objective-c push-notification notifications

我正在使用带有开发配置文件的推送应用程序来获取Rich推送通知,并在iOS上的通知中心右侧附加图像,但我无法获得通知上的图像,而我可以看到标题,副标题和身体在推。我是否需要在通知服务扩展中执行任何其他代码?

{"aps" : {
        "alert" : {
            "title" : "Introduction To Notification",
            "subtitle" : "Session 707",
            "body" : "New Notification Look Amazing"
        },
       "sound" : "default",
        "category" : "message",
        "badge" : 1,
        "mutable-content": 1
    },
    "attachment-url": "https://i.imgur.com/t4WGJQx.jpg"
}

1 个答案:

答案 0 :(得分:0)

是的,您需要自己下载图像,并在下载完成后调用完成处理程序。

您的“通知扩展”必须有一个viewController,您可能已在故事板中添加了名为“mainInterface.storyBoard”的UI。所以在你的viewcontroller类中我们说NotificationViewController,它需要实现protocol:UNNotificationContentExtension,然后你可以实现的委托方法:

class NotificationViewController: UIViewController, UNNotificationContentExtension {

@IBOutlet weak var imageView: UIImageView!

override func viewDidLoad() {
    super.viewDidLoad()
    // Do any required interface initialization here.
}

func didReceive(_ notification: UNNotification) {
    if let urlString = notification.request.content.userInfo["attachment-url"] as! String? {
        if let imageURL = URL(string: urlString) {
            if let data = NSData(contentsOf: imageURL) {
                self.imageView.image = UIImage(data: data as Data)
            }    
        }
    }  
  }
}

此处图像视图是视图控制器中添加的图像视图的插座。

P.S。您需要将框架导入为:

import UserNotifications
import UserNotificationsUI

您可以参考自定义通知教程here