App goes background instead of open an URL

502 Views Asked by At

I implemented local notifications and want to open an URL when the notification is tapped. Here is the code which should do it:

- didFinishLaunchingWithOptions 

    UILocalNotification *notification = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];

if(notification != nil){
    NSDictionary *userInfo = notification.userInfo;
    NSURL *siteURL = [NSURL URLWithString:[userInfo objectForKey:@"linkToOpen"]];
    dispatch_async(dispatch_get_main_queue(), ^{
        if ([[UIApplication sharedApplication] canOpenURL:siteURL]){
            [[UIApplication sharedApplication] openURL:siteURL];
        }
    });

and didReceiveLocalNotification:

-(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification{
dispatch_async(dispatch_get_main_queue(), ^{
    NSDictionary *userInfo = notification.userInfo;
    NSURL *siteURL = [NSURL URLWithString:[userInfo objectForKey:@"linkToOpen"]];
    NSLog(@"try to open url:%@", siteURL.absoluteString);
    if([[UIApplication sharedApplication] canOpenURL:siteURL]){
        [[UIApplication sharedApplication] openURL:siteURL];
    }

});

When the app is in background or not running at the moment the notification is tapped, the code in didFinishLaunchingWithOptions is called and everything is working fine. Even if the app is attached to xCode debugger and is in foreground it is working (after some delay), but if the app is in foreground and NOT attached to debugger, then the app goes background instead of open the url. I don't know what happen, because I don't get any information of the app state without debugger information. The url is always the same, so there can't be a problem. I can't understand why it is working while debugging session but not while normal one, even if it is the same debug build on the same device. Would be very thankful for every idea!

1

There are 1 best solutions below

2
On

Try to add short deley for application launching time.

dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
    NSDictionary *userInfo = notification.userInfo;
    NSURL *siteURL = [NSURL URLWithString:[userInfo objectForKey:@"linkToOpen"]];
    NSLog(@"try to open url:%@", siteURL.absoluteString);
    if([[UIApplication sharedApplication] canOpenURL:siteURL]){
        [[UIApplication sharedApplication] openURL:siteURL];
    }
})