ios - 丰富的本地通知

标签 ios swift swift4 uilocalnotification rich-notifications

我们如何才能像过去在丰富的通知中显示的那样在本地通知中显示图像或任何附件?

我正在接收静默通知,然后在本地通知中更改它。

最佳答案

是的,你也可以在本地通知中显示它,你必须在收到静默推送后触发本地通知,我希望你的静默通知负载中所有需要的数据都在那里。

这是代码片段

let content = UNMutableNotificationContent()

//Configure notification 

content.title = "Notification Title"
content.body = "Notification Body"
content.sound = UNNotificationSound.default()  
content.categoryIdentifier = "ImageNotification"


//Attach your image local path here (Document dir path)

let attachment = try! UNNotificationAttachment(identifier: "\(NSDate().timeIntervalSince1970 * 1000)", url: localURL, options: [:])
content.attachments = [attachment]


content.userInfo = ["attachmentType": "Media"]

// Create a trigger for fire a local notification

let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.2, repeats: false)        
let request = UNNotificationRequest(identifier: "\(NSDate().timeIntervalSince1970 * 1000)", content: content, trigger: trigger)

// Configure according to version

if #available(iOS 11.0, *) {
let contactCategory = UNNotificationCategory(identifier: content.categoryIdentifier,
                                                         actions: [],
                                                         intentIdentifiers: [],
                                                         hiddenPreviewsBodyPlaceholder: "",
                                                         options: .customDismissAction)
let notificationCenter = UNUserNotificationCenter.current()
            notificationCenter.setNotificationCategories([contactCategory])
} else {
        // Fallback on earlier versions

let contactCategory = UNNotificationCategory(identifier: content.categoryIdentifier, actions: [], intentIdentifiers: [], options: [])
            let notificationCenter = UNUserNotificationCenter.current()
            notificationCenter.setNotificationCategories([contactCategory])
        }


UNUserNotificationCenter.current().add(request) {[weak self] (error) in
    guard error == nil else { 
                return
    }
}

此实现后它会正常工作,如果您仍然遇到任何问题,请告诉我。

关于ios - 丰富的本地通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52772446/

相关文章:

iOS - CALayer 和手势/滑动识别器

ios - iPhone 应用程序在设备中崩溃,但它在模拟器中运行

ios - Swift 4 - 'substring(to:)' 已弃用 - 替代我的代码

ios - 将数据从 MainView 传递到 ContainerView

ios - Storyboard segue 导致 AVAudioEngine 崩溃

ios - 将 UIButton 字体大小调整为宽度

ios - 在同一行上使用两次“滑动删除”功能时应用程序崩溃

ios - 从 Swift 指定 Objective-C 闭包变量名称

iOS 向 UITableView 添加图像导致显示时间过长

ios - 从 Swift 4 新的键路径语法获取字符串?