如何在iOS推送通知中显示图片?

60

iOS 10引入了推送通知框架更新,

UserNotificationsUI.framework

根据苹果文档所述,它允许我们在用户设备上显示本地和远程通知时自定义外观。

因此,如果有人知道如何在锁定屏幕上显示推送通知中的图像。与安卓推送通知相同。

谢谢,


您可以观看WWDC开发者视频,其中在“丰富的通知”课程中有相关解释。 - Tolgay Toklar
2
如果有人需要:- 我在下面的博客文章中找到了解决方案:(从远程通知的URL加载图像)[http://www.avanderlee.com/ios-10/rich-notifications-ios-10/]并且不要忘记在您的有效负载中添加一行:“mutable_content”:true, - Touhid
文档:https://developer.apple.com/documentation/usernotifications/setting_up_a_remote_notification_server/generating_a_remote_notification 和 https://developer.apple.com/documentation/usernotifications/modifying_content_in_newly_delivered_notifications - Nike Kov
3
顶部的答案是误导性的。为什么?因为提问者询问的是有关远程通知的问题。但是答案主要展示了如何在创建通知时附加和嵌入图像 — 本地的方式。唯一能够让远程通知显示其图像的方法是使用NotificationServiceExtensionNotificationContentExtension不起作用,因为它只是呈现传递给它的现有内容。附件必须在NotificationServiceExtension中本地传递或下载。有关更多信息,请参见 https://developer.apple.com/videos/play/wwdc2016/708/。 - mfaani
5个回答

91
如果您想自定义本地和远程通知的外观,请执行以下步骤:
  1. 创建一个 UNNotificationCategory 并将其添加到 UNUserNotificationCenter 类别中:

    let newCategory = UNNotificationCategory(identifier: "newCategory",
                                             actions: [ action ],
                                             minimalActions: [ action ],
                                             intentIdentifiers: [],
                                             options: [])
    
    let center = UNUserNotificationCenter.current()
    
    center.setNotificationCategories([newCategory])
    
  2. 创建一个UNNotificationContentExtension:

enter image description here

然后使用代码或者Storyboard自定义你的UIViewController

  1. UNNotificationContentExtension的plist文件中添加分类:

enter image description here

4.推送通知

本地通知

创建一个UNMutableNotificationContent对象并将其categoryIdentifier设置为“newCategory”,其中包含了UNUserNotificationCenter的分类和UNNotificationContentExtension的plist文件:

let content = UNMutableNotificationContent()
content.title = ...
content.body = ...
content.categoryIdentifier = "newCategory"

let request = UNNotificationRequest.init(identifier: "newNotificationRequest", content: content, trigger: nil)

let center = UNUserNotificationCenter.current()
center.add(request)

远程通知

设置 "mutable-content : 1""category : newCategory"。请注意,类别值设置为 "newCategory",与之前添加到 UNUserNotificationCenterUNNotificationContentExtension的 plist 文件匹配。

示例:

 {
    "aps" : {
        "alert" : {
        "title" : "title",
        "body" : "Your message Here"
        },
        "mutable-content" : "1",
        "category" : "newCategory"
    },
    "otherCustomURL" : "http://www.xxx.jpg"
 }
  1. 注意:你需要一个支持3DTouch的设备或模拟器,否则无法显示自定义的UNNotificationContentExtension视图控制器。(在iOS10 Beta1中,这是无效的。但现在不需要3D Touch即可使用)

而且...如果你只想在锁屏界面上显示推送通知中的图片,你需要添加UNNotificationAttachment

let content = UNMutableNotificationContent()
content.title = ...
content.body = ...
content.categoryIdentifier = "newCategory"

let fileURL: URL = ... //  your disk file url, support image, audio, movie

let attachement = try? UNNotificationAttachment(identifier: "attachment", url: fileURL, options: nil)
content.attachments = [attachement!]

let request = UNNotificationRequest.init(identifier: "newNotificationRequest", content: content, trigger: nil)

let center = UNUserNotificationCenter.current()
center.add(request)

enter image description here

如需更详细的功能信息,请参考演示


1
@maquannene 我相信你必须设置 "mutable-content": 1,即整数 1,而不是字符串 "1",我错了吗? - BigRon
1
UNNotificationAttachment中的“附件”指的是什么——标识符是什么?我在这行代码中遇到了错误-(在解包可选值时意外发现nil)。 - Abirami Bala
1
@maquannene:你能否添加一个简单的演示项目,展示如何在远程通知中显示图片? - Abhishek Thapliyal
@AbhishekThapliyal。是的,问题解决了,请查看此链接,如果需要,我可以分享示例代码。谢谢... - Abirami Bala
4
这个回答是误导性的。为什么?因为提问者正在询问关于远程通知的问题,但这个回答主要展示了当通知被创建时如何附加和嵌入图片 —— 本地的方式。想要让远程通知显示它的图片,唯一的方法是使用NotificationServiceExtensionNotificationContentExtension 不适用,因为它只是为了呈现传递给它的现有内容。该附件必须在NotificationServiceExtension中通过本地传递或下载。更多信息请参见 https://developer.apple.com/videos/play/wwdc2016/708/ - mfaani
显示剩余12条评论

13

实际上,如果您正在设置本地通知并且只想在通知本身中显示图像,则根本不需要涉及NotificationsUI.framework或UNNotificationContentExtensions。只有在您希望用户3D触摸或扩展通知时使用自定义UI时,才有用。

要添加已经存在于设备上的图像(可以是随应用程序一起提供的图像,也可以是在创建通知之前应用程序生成/存储的图像),则只需要使用文件URL添加一个UNNotificationAttachment,其中路径以.png结尾(.jpg可能也有效?)。类似这样:

UNMutableNotificationContent *content = [UNMutableNotificationContent new];
content.title = @"Title";
content.body = @"Body";
content.sound = [UNNotificationSound defaultSound];
NSURL *imageURL = [NSURL URLWithString:@"file:/some/path/in/app/image.png"];
NSError *error;
UNNotificationAttachment *icon = [UNNotificationAttachment attachmentWithIdentifier:@"image" URL:imageURL options:nil error:&error];
if (error)
{
    NSLog(@"error while storing image attachment in notification: %@", error);
}
if (icon)
{
    content.attachments = @[icon];
}

当通知出现时,图片将会像消息通知一样显示在通知横幅的右侧。而且你不需要通过设置带有categoryIdentifier的内容扩展等方式来完成。

编辑:更新以添加这只是本地通知的有效解决方案。


1
这个适用于远程文件路径吗?例如 https://www.webservice/images/myimage.png? - user1904273
抱歉,我没有尝试过,所以我不知道它是否有效。为什么不试一试看看它是否有效呢? - Greg G

5

您需要在创建推送通知时进行一些工作,以及在处理时进行一些操作。

  1. When you creating payload you need to add extra attribute attachment, something like below:

    {        
        aps : {
            alert: { },
            mutable-content:1
        }
        my-attachment = "url to resource"
    }
    
  2. When you receive notification system will call didReceive method of service extension, override notification extension didReceive method like this

    public func didReceive(_ request:UNNotificationRequest, withContentHandler contentHandler:(UNNotificatinContent) -> Void) {
        let fileUrl = //
        let attachment = UNNotificationAttachment(identifier : "image", url: fileUrl, options: nil)
        let content = request.content.mutableCopy as! UNMutableNotificationContent
        content.attachment = [attachment]
        contentHandler(content)
    }
    

这里是关于此主题的WWDC视频讲座。


1
mutable-content是需要添加到aps字典中的关键字。 - Luke
3
您还需要下载该图像。 - Luke

1
使用Netmera SDK 3.14.4版本,您无需添加桥接头文件即可使用iOS 10媒体推送。您只需要在通知服务扩展中实现以下方法来接收富媒体推送。 您可以同时支持Swift和Objective-C。 步骤1 从项目中移除Objective-C桥接头文件,并在NotificationService.swift文件中添加:import NetmeraNotificationServiceExtension
target 'your_service_extension_target_name' do

 pod "Netmera/NotificationServiceExtension"

end

在将上述行添加到您的Podfile后,使用`pod update`。 第二步 确保您已安装Xcode 8或更高版本。如果没有,请升级您的Xcode安装以在应用程序上使用iOS10媒体推送。 首先,您应该为您的应用程序创建一个新的通知服务扩展。为了做到这一点,您应该按照以下步骤进行操作:
  • 打开Xcode并导航到"文件"->"新建"->"目标"

enter image description here

选择可用选项中的通知服务扩展。

enter image description here

第三步
将创建一个名为“NotificationService”的新类,该类应该从“NetmeraNotificationServiceExtension”类继承。您的NotificationService类应该如下所示,
class NotificationService : NetmeraNotificationServiceExtension {

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

    override func serviceExtensionTimeWillExpire() {
        super.serviceExtensionTimeWillExpire()
    }

}

将"Netmera.framework"链接到通知服务扩展。为此,请在Podfile中将您的通知服务扩展添加为目标,包括以下行:
pod "Netmera/NotificationServiceExtension"

更新您的Podfile以安装必要的依赖项并执行链接过程。
此外,如果您想了解更多关于发送轮播、滑块通知的信息,请查看这里

-2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接