我正在尝试获取活动的通知列表。
如果应用程序已启动且处于活动状态,我会获取数据,但是如果徽章计数器显示的新通知数> 0,则在应用程序启动时关闭应用程序启动时收到通知,则通知数组为空事件。
NotificationManager.swift
import Foundation
import UserNotifications
struct Notification: Encodable {
var field1: String?
var field2: String?
}
func isAnyNil(optionals: Optional<Any> ...) -> Bool {
return optionals.contains { $0 == nil }
}
@available(iOS 10.0, *)
func json(from notifications:Array<UNNotification>) -> String? {
if #available(iOS 10.0, *) {
var formattedNotifications = [Notification]()
for i in 0..<notifications.count {
let rec = notifications[i] as? UNNotification
print("--------------NOTIFICATION-----------------")
let aps = rec?.request.content.userInfo["aps"] as? NSDictionary
let alert = aps?["alert"] as? NSDictionary
let title = alert?["field1"] as? String
let body = alert?["field2"] as? String
if (isAnyNil(optionals: field1, field2)) { continue }
formattedNotifications.append(Notification(
info1: field1,
info2: field2
))
}
print("----- BEFORE JSON CONVERSION ------")
print(formattedNotifications)
do {
let jsonData = try JSONEncoder().encode(formattedNotifications)
let jsonString = String(data: jsonData, encoding: .utf8)!
return(jsonString)
} catch { return "[]" }
} else {
return "[]"
}
}
@objc(NotificationManager)
class NotificationManager: NSObject {
@objc static func requiresMainQueueSetup() -> Bool {
return true
}
@objc func getActiveNotifications(_ resolve: @escaping RCTPromiseResolveBlock,
rejecter reject: @escaping RCTPromiseRejectBlock ) -> Void {
if #available(iOS 10.0, *) {
UNUserNotificationCenter.current().getDeliveredNotifications(completionHandler: { (notifications) in
resolve(json(from: notifications))
})
} else {
reject("Not available", "Not supported", nil);
}
}
}
OneSignalNotificationServiceExtension的Info.plist :
<key>OneSignal_disable_badge_clearing</key>
<true/>
AppDelegate.m
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
}
// Required for the register event.
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
}
- (void) application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
NSLog(@"Registering device failed: %@", error);
}
// Required for the localNotification event.
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification
{
[RCTPushNotificationManager didReceiveLocalNotification:notification];
}
对于我来说,这不是很清楚,是否可以在应用启动时关闭应用后启动。我已经读过一些帖子,通知仅缓存了几分钟,但是在应用程序启动时,我什至没有收到过去30-60秒内收到的通知。...