[英]Unable to listen notification from NSNotificationCenter when App received push notification from background or terminated in iOS
我正在iOS 10中實現推送通知。一切正常。
但是,當APP收到推送通知時(不僅處於活動狀態,而且處於后台/終止狀態),我都需要點擊API。
為此,我使用NSNotificationCenter
來監聽應用程序收到如下推送通知時的通知:
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
willPresentNotification:(UNNotification *)notification
withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
NSDictionary *userInfo = notification.request.content.userInfo;
NSLog(@"Message ID: %@", userInfo[@"gcm.message_id"]);
NSLog(@"%@", userInfo);
if( [UIApplication sharedApplication].applicationState == UIApplicationStateInactive )
{
NSLog( @"INACTIVE" );
completionHandler( UNNotificationPresentationOptionAlert );
}
else if( [UIApplication sharedApplication].applicationState == UIApplicationStateBackground )
{
NSLog( @"BACKGROUND" );
completionHandler( UNNotificationPresentationOptionAlert );
}
else
{
NSLog( @"FOREGROUND" );
completionHandler( UNNotificationPresentationOptionAlert );
}
[[NSNotificationCenter defaultCenter] postNotificationName:@"reloadTheTable" object:nil];
}
我像這樣在ViewController.m
監聽此通知
- (void)viewDidLoad {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadTable:) name:@"reloadTheTable" object:nil];
}
- (void)reloadTable:(NSNotification *)notification
{
// Calling API here
}
當應用程序在前台運行時,這工作正常。 但不在背景和終止狀態。
我是否有任何錯誤或需要實施的其他任何措施?
從iOS 10開始,我們必須添加UserNotifications框架並委托
所以首先我們需要在appDelegate.h中做以下事情
#import <UserNotifications/UserNotifications.h>
@interface AppDelegate : UIResponder <UIApplicationDelegate,UNUserNotificationCenterDelegate>
對於FOREGROUND狀態
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
willPresentNotification:(UNNotification *)notification
withCompletionHandler:(void (^)(UNNotificationPresentationOptions options))completionHandler
{
NSLog( @"Handle push from foreground" );
// custom code to handle push while app is in the foreground
NSLog(@"%@", notification.request.content.userInfo);
}
這是背景狀態 。
所以在這里您需要添加通知
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
withCompletionHandler:(void (^)())completionHandler
{
NSLog( @"Handle push from background or closed" );
// if you set a member variable in didReceiveRemoteNotification, you will know if this is from closed or background
NSLog(@"%@", response.notification.request.content.userInfo);
//Adding notification here
[[NSNotificationCenter defaultCenter] postNotificationName:@"reloadTheTable" object:nil];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.