Objective-C iPhone - Open URL in Safari immediately and exit app

user3724252 picture user3724252 · Jun 10, 2014 · Viewed 14.9k times · Source

I am able to open a URL in Safari using:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"www.myurl.com"]];

It works fine, but it takes more than 10 seconds in the Simulator. I've tried putting this code inside the app delegate's didFinishLauchingWithOptions method or my view controller's viewDidLoad method, but it still takes over 10 seconds to load. I get a black screen with nothing on it for that entire duration before it suddenly opens Safari. Is there any way I could decrease the load time? Is this only a Simulator bug?? I am still trying to get my devices registered to test on actual devices.

The funny thing is that when I add it to a UIButton's action method, the app loads right away, but the user must tap the UIButton to launch the URL in Safari.

My objective here is to have an app that upon startup, immediately launches a hard-coded URL in safari. The app should immediately exit so that it will be able to do this again when the user taps on the app icon. Any suggestions?

Here's a snippet of what I attempted before in my ViewController.m that has the 10 second black screen if you want to try it yourself:

- (void)viewDidLoad
{
    [super viewDidLoad];
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"www.myurl.com"]];
    exit(0);
}

Answer

Joey picture Joey · Jun 10, 2014

Why don't you use Add to Home Screen at Mobile Safari?

enter image description here

However if you want to call Safari at the beginning of launching the app, try this:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    // Override point for customization after application launch.


    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.google.com"]];
        exit(0);
    });

    return YES;
}