ios 如何在ios推送通知中显示图像?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37839171/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 09:24:08  来源:igfitidea点击:

how to display image in ios push notification?

iospush-notificationapple-push-notificationsios10unnotificationserviceextension

提问by Parth Pandya

iOS 10 introduced push notification framework updates,

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

UserNotificationsUI.framework

UserNotificationsUI.framework

As written on apple docs, it lets us customize the appearance of local and remote notifications when they appear on the user's device.

正如 Apple 文档中所写,当本地和远程通知出现在用户的设备上时,它让我们可以自定义它们的外观。

So if anyone have idea how to display image in push notification when on lock screen. same like andorid push notification are doing.

因此,如果有人知道如何在锁定屏幕上的推送通知中显示图像。就像andorid推送通知正在做的一样。

Thanks,

谢谢,

回答by maquannene

If you want to customize the appearance of local and remote notifications, perform the following steps:

如果要自定义本地和远程通知的外观,请执行以下步骤:

  1. Create a UNNotificationCategoryand add to the UNUserNotificationCentercategory:

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

  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

在此处输入图片说明

then use code or storyboard to customize your UIViewController.

然后使用代码或故事板来自定义您的UIViewController.

  1. Add category to UNNotificationContentExtension's plist:
  1. 将类别添加到UNNotificationContentExtension的 plist:

enter image description here

在此处输入图片说明

4.Push Notification

4.推送通知

Local Notification

本地通知

Create a UNMutableNotificationContentand set the categoryIdentifierto "newCategory" which includes UNUserNotificationCenter's categories and UNNotificationContentExtension's plist:

创建一个UNMutableNotificationContent并将其设置categoryIdentifier为“newCategory”,其中包括UNUserNotificationCenter的类别和UNNotificationContentExtensionplist:

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)

Remote Notification

远程通知

Set "mutable-content : 1"and "category : newCategory". Note that the category value is set to "newCategory" which matches what you previously added to UNUserNotificationCenterand UNNotificationContentExtensions plist.

设置"mutable-content : 1""category : newCategory"。请注意,类别值设置为“newCategory”,它与您之前添加的内容UNUserNotificationCenterUNNotificationContentExtensions plist相匹配。

Example:

例子:

 {
    "aps" : {
        "alert" : {
        "title" : "title",
        "body" : "Your message Here"
        },
        "mutable-content" : "1",
        "category" : "newCategory"
    },
    "otherCustomURL" : "http://www.xxx.jpg"
 }
  1. Note: you need a device or simulator which supports 3DTouch, otherwise you can't show a custom UNNotificationContentExtensionviewcontroller.(In iOS10 Beta1, it`s not work. But now this work without 3d touch)
  1. 注意:需要支持3DTouch的设备或模拟器,否则无法显示自定义UNNotificationContentExtensionviewcontroller。(在iOS10 Beta1中是不行的。但现在这项工作没有3d touch)

And ... if you just want to show an image on a push notification displayed on the lock screen, you need to add UNNotificationAttachment:

并且...如果您只想在锁定屏幕上显示的推送通知上显示图像,则需要添加 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

在此处输入图片说明

For more detail feature,Demo

欲了解更多详细功能,Demo

回答by Greg G

Actually if you are setting up a local notification and you're just interested in having an image show up in the notification itself, you don't have to bother with NotificationsUI.framework or UNNotificationContentExtensions at all. That is only useful if you want a custom UI when the user 3D touches or expands the notification.

实际上,如果您正在设置本地通知并且您只是对在通知中显示图像感兴趣,那么您根本不必理会 NotificationsUI.framework 或 UNNotificationContentExtensions。这仅在用户 3D 触摸或展开通知时想要自定义 UI 时才有用。

To add an image that is already on the device (either shipped with the app, or generated/stored by the app at some point before the notification is created), then you only need to add a UNNotificationAttachment with a file URL where the path ends in .png (or .jpg will likely work too?). Something like this:

要添加设备上已有的图像(应用程序附带的图像,或者在创建通知之前的某个时间点由应用程序生成/存储的图像),那么您只需要添加带有路径结尾的文件 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];
}

Then when the notification appears, the image will show up on the right-hand side of the notification banner like it does for Messages notifications. And you don't have to jump through all of the hoops of setting up a content extension with a categoryIdentifier, etc.

然后当通知出现时,图像将显示在通知横幅的右侧,就像消息通知一样。而且您不必跳过使用 categoryIdentifier 等设置内容扩展的所有环节。

EDIT: Updated to add that this is only a valid solution for local notifications.

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

回答by Adnan Aftab

You have to do some work on creating push notification and also when you are handling.

您必须在创建推送通知以及处理时做一些工作。

  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 didReceivemethod of service extension, override notification extension didReceivemethod 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)
    }
    
  1. 创建有效负载时,您需要添加额外的属性附件,如下所示:

    {        
        aps : {
            alert: { },
            mutable-content:1
        }
        my-attachment = "url to resource"
    }
    
  2. 当您收到通知系统将调用didReceive服务扩展didReceive方法,像这样覆盖通知扩展方法

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

Hereis WWDC video talk on this topic.

是关于这个主题的 WWDC 视频演讲。

回答by Peter Cetinski

Implement your notification's custom view using a UIViewController that conforms to UNNotificationContentExtension.

使用符合 UNNotificationContentExtension 的 UIViewController 实现通知的自定义视图。

See https://developer.apple.com/reference/usernotificationsui/unnotificationcontentextension

请参阅https://developer.apple.com/reference/usernotificationsui/unnotificationcontentextension