我实际上是通过JSON和消息接收通知的,所以我想要的是处理通知并将其显示给用户。
当应用程序没有运行或在后台时,消息会显示,但当应用程序打开时,没有通知。事实上,我在didReceiveRemoteNotification
时收到了json,但我想要的是一个像whatsapp做的那样的通知框。
就像这样:
我有这个:
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
print("Notification received: \(userInfo)")
let notification = userInfo["aps"] as? NSDictionary
let message = notification?.valueForKey("alert")
}
而这在didfinishlaunchWithOptions
let readAction = UIMutableUserNotificationAction()
readAction.identifier = "READ_IDENTIFIER"
readAction.title = "Read"
readAction.activationMode = UIUserNotificationActivationMode.Foreground
readAction.destructive = false
readAction.authenticationRequired = true
let deleteAction = UIMutableUserNotificationAction()
deleteAction.identifier = "DELETE_IDENTIFIER"
deleteAction.title = "Delete"
deleteAction.activationMode = UIUserNotificationActivationMode.Foreground
deleteAction.destructive = true
deleteAction.authenticationRequired = true
let ignoreAction = UIMutableUserNotificationAction()
ignoreAction.identifier = "IGNORE_IDENTIFIER"
ignoreAction.title = "Ignore"
ignoreAction.activationMode = UIUserNotificationActivationMode.Foreground
ignoreAction.destructive = false
ignoreAction.authenticationRequired = false
let messageCategory = UIMutableUserNotificationCategory()
messageCategory.identifier = "MESSAGE_CATEGORY"
messageCategory.setActions([readAction, deleteAction], forContext: UIUserNotificationActionContext.Minimal)
messageCategory.setActions([readAction, deleteAction, ignoreAction], forContext: UIUserNotificationActionContext.Default)
let types: UIUserNotificationType = [UIUserNotificationType.Badge, UIUserNotificationType.Sound, UIUserNotificationType.Alert]
application.registerUserNotificationSettings(
UIUserNotificationSettings(
forTypes: types,
categories: (NSSet(array: [messageCategory])) as? Set<UIUserNotificationCategory>))
UIApplication.sharedApplication().registerForRemoteNotifications()
let notTypes:UIUserNotificationType = [UIUserNotificationType.Alert, UIUserNotificationType.Badge, UIUserNotificationType.Sound]
let noteSettings:UIUserNotificationSettings = UIUserNotificationSettings(forTypes: notTypes, categories: nil)
UIApplication.sharedApplication().registerUserNotificationSettings(noteSettings)
希望有人能帮上忙。谢谢大家
3条答案
按热度按时间9q78igpj1#
当你的应用程序在前台时,iOS不会显示通知横幅。你必须显示你自己。你可以使用第三种代码来显示横幅,并处理横幅上的触摸,以处理适当的代码:
https://github.com/KrauseFx/TSMessageshttps://github.com/terryworona/TWMessageBarManager显示器
在回调didReceiveRemoteNotification中,检查应用程序状态:
jtoj6r0c2#
您只需要创建一个视图,用您的内容自定义它,并在应用程序窗口中显示它。
还有一些框架可以帮您完成这些工作,例如CWStatusBarNotification
mepcadol3#
你不需要使用额外的框架或库,在iOS 10中,你可以使用
userNotificationCenter(_:willPresent:withCompletionHandler:)
方法。只有当您将属性
content-available:1
添加到有效负载时,才会调用此方法。有效负载应类似于: