0

我在iOS 10中實施推送通知。一切正常。當應用程序收到來自後臺的推送通知或在iOS中終止時,無法收聽來自NSNotificationCenter的通知

但是,當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 
} 

這是工作很好,當應用程序在前臺運行。 但不在後臺並終止狀態。

是否有我或我必須執行的其他任何錯誤?

+0

我更新了我的答案,請檢查它現在 – user3182143

回答

2

從iOS的10,我們必須添加UserNotifications框架,並委託

所以首先我們需要做以下事情appDelegate.h

#import <UserNotifications/UserNotifications.h> 
@interface AppDelegate : UIResponder <UIApplicationDelegate,UNUserNotificationCenterDelegate> 

對於前臺狀態

- (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]; 
} 

didReciveRemoteNotificationNotCalled in iOS 10

+0

這是確定的對我,但不能調用其他方法時,應用程序在後臺 – Himanth

+0

現在檢查它。一旦它有效,讓我知道。 – user3182143

+0

它工作與否? – user3182143

相關問題