【发布时间】:2016-10-14 12:56:54
【问题描述】:
我想在应用程序处于前台时显示通知。下面是我为新的 usernotificationdelegate 方法做的代码。
在应用委托中:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
//iOS 10 handling
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
[center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert) completionHandler:^(BOOL granted, NSError * _Nullable error) {
if (!error) {
NSLog(@"request authorization succeeded!");
} }];
}
}
#pragma mark - User notification delegate
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler {
NSLog(@"willPresentNotification");
NSLog(@"%@", notification.request.content.userInfo);
completionHandler (UNNotificationPresentationOptionAlert);
}
这是我触发本地通知的方法
-(void) fireLocalNotification:(NSString *) message
{
NSLog(@"fire Local Notification");
if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"10.0")) {
//Notification Content
UNMutableNotificationContent *content = [[UNMutableNotificationContent alloc] init];
content.body = [NSString stringWithFormat:@"%@",message];
content.sound = [UNNotificationSound defaultSound];
//Set Badge Number
content.badge = @([[UIApplication sharedApplication] applicationIconBadgeNumber] + 1);
// Deliver the notification in five seconds.
UNTimeIntervalNotificationTrigger *trigger = [UNTimeIntervalNotificationTrigger
triggerWithTimeInterval:1.0f repeats:NO];
//Notification Request
UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@"LocalNotification" content:content trigger:trigger];
//schedule localNotification
UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
center.delegate = self;
[center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
if (!error) {
NSLog(@"add Notification Request succeeded!");
}
}];
}
}
现在这样做之后我仍然没有在前台收到通知。
提前致谢。
【问题讨论】:
-
参考我的回答from here它可能对你有帮助!
-
willPresentNotification是否出现在控制台日志中?如果应用不在在前台,您会看到通知警报吗? -
是的@matt,当我的应用程序不在前台时,我会看到警报,即通知,但它没有出现在前台。
-
@Lion,您提到的答案是针对 UILocalNotification。我想使用 iOS 10 UserNotification 框架。用于在前台显示通知。
-
另外,还有一件事……我已经设置了委托,但没有调用 UserNotification 委托。
标签: ios objective-c uilocalnotification unusernotificationcenter