如何使用 Objective c 在 iOS 中单击通知时打开视图控制器



我正在使用目标c在iOS中开发简单的应用程序。在我的应用程序中,我添加了通知。它工作正常,来自服务器的通知,也向用户显示。所以我需要 如何在单击通知时打开视图控制器? 我正在寻找一种在点击收到的通知后打开视图并在该视图上显示通知以允许用户读取通知信息的方法。有人可以帮助我吗?

在 AppDelegate.m 类中添加以下 Delegate 方法

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler 

每当应用收到此委托方法将调用的通知时,都可以在此处处理逻辑。下面是简单的逻辑

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    NSLog(@"didReceiveRemoteNotification with completionHandler");
    // Must call completion handler
    if (userInfo.count > 0) {
        completionHandler(UIBackgroundFetchResultNewData);
    } else {
        completionHandler(UIBackgroundFetchResultNoData);
    }
    NSLog(@"userInfo:%@", userInfo);    
    __weak typeof (self) weakSelf = self;
    dispatch_async(dispatch_get_main_queue(), ^{
        __strong typeof(weakSelf) strongSelf = weakSelf;
        SEL openDetails = @selector(openDetailsViewFromNotificationInfo:);
        //The below line will removes previous request.
        [NSObject cancelPreviousPerformRequestsWithTarget:strongSelf selector:openDetails object:userInfo];
        //Not neccessary 
        [strongSelf performSelector:openDetails withObject:userInfo afterDelay:0.5];
    });
}
-(void)openDetailsViewFromNotificationInfo:(NSDictionary *)userInfo {
    UINavigationController *navVC = (UINavigationController *)self.window.rootViewController;
    UIViewController *topVC = navVC.topViewController;
    NSLog(@"topVC: %@", topVC);
    //Here BaseViewController is the root view, this will initiate on App launch also.
    if ([topVC isKindOfClass:[BaseViewController class]]) {
        BaseViewController *baseVC = (BaseViewController *)topVC;
        if ([baseVC isKindOfClass:[YourHomeVC class]]) {
            YourHomeVC *homeVC = (YourHomeVC *)baseVC;
            homeVC.notificationUserInfo = userInfo;
        }
    }
}

最新更新