Skip to content

Instantly share code, notes, and snippets.

@greenisus
Created July 10, 2012 03:57
Show Gist options
  • Save greenisus/3080870 to your computer and use it in GitHub Desktop.
Save greenisus/3080870 to your computer and use it in GitHub Desktop.
Preference for open in Chrome or Safari
#define kBrowserPref @"browserPref"
- (IBAction)openInBrowserButtonPressed:(id)sender {
NSString *myURL = nil; // put however you get the URL here
// can we open in Chrome?
if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"googlechrome:"]]) {
// let's check the preference
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if (![defaults stringForKey:kBrowserPref]) {
// no preference chosen, so present the option
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Open in Safari", @"Open in Chrome", nil];
[actionSheet showInView:self.view];
} else if ([[defaults stringForKey:kBrowserPref] isEqualToString:@"chrome"]) {
// they want Chrome, so give them Chrome!
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"googlechrome://%@", myURL]]];
} else {
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@", myURL]]];
}
} else {
// can't open in Chrome, so just use Safari
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@", myURL]]];
}
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
NSString *myURL = nil; // put however you get the URL here
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSURL *url = nil;
if (buttonIndex == 0) {
url = [NSURL URLWithString:[NSString stringWithFormat:@"googlechrome://%@", myURL]];
[defaults setValue:@"chrome" forKey:kBrowserPref];
} else {
url = [NSURL URLWithString:[NSString stringWithFormat:@"%@", myURL]];
[defaults setValue:@"safari" forKey:kBrowserPref];
}
[defaults synchronize];
[[UIApplication sharedApplication] openURL:url];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment