Mohamed Ali
Mohamed Ali

Reputation: 59

How to open a view controller on click a notification in iOS using Objective c?

I am developing simple app in iOS using objective c. In my app I added notification. It works fine and notification from server and also appears to the users. So that I need How to open a view controller on click a notification? I'm searching for a method to open a view after tapping on a notification received and display notification on that view to allow the users to read notification information. can any one help me?

Upvotes: 0

Views: 993

Answers (1)

svs
svs

Reputation: 257

In your AppDelegate.m class add the below Delegate method

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

Whenever App gets a notification this delegate method will call, You can handle your logic here. Below is the simple logic

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

Upvotes: 1

Related Questions