1. 程式人生 > >iOS區分點選Notification時程式是啟動狀態或是未啟動狀態

iOS區分點選Notification時程式是啟動狀態或是未啟動狀態

最近在使用Firebase做React Native的推送功能,分別在Android和iOS端集成了Firebase的CloudMessaging,其中有一個需求就是當用戶收到Notification並點選時,能判斷出App是啟動(前臺,或者按Home隱藏)還是未啟動狀態,從而做不同的響應.
具體怎麼做區分呢? 請看程式碼:

@interface AppDelegate () <UNUserNotificationCenterDelegate>
@end

@implementation AppDelegate
- (BOOL)application:(UIApplication
*)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { if (launchOptions) { NSDictionary *userInfo = [launchOptions valueForKey:UIApplicationLaunchOptionsRemoteNotificationKey]; if ([userInfo isKindOfClass:[NSDictionary class]]) { //位置 ① //程式碼走到這裡,說明使用者點選Notification時,app是未啟動狀態
} } return YES; } - (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void(^)(void))completionHandler { completionHandler(); NSDictionary * userInfo = response.notification
.request.content.userInfo; NSLog(@"userInfo %@", userInfo); if ([userInfo isKindOfClass:[NSDictionary class]]) { //位置 ② //Notification點選後,不論App啟動或未啟動都會走到這裡 //但是會晚於didFinishLaunchingWithOptions執行 //所以程式碼只執行了位置②,代表使用者點選Notification時,程式是啟動狀態 } } @end