12

Does UIApplication:openURL work?

NSString *iTunesLink = @"http://www.youtube.com/watch?v=TFFkK2SmPg4";
BOOL did = [[UIApplication sharedApplication] openURL:[NSURL URLWithString:iTunesLink]];

This does nothing.

Daniel Storm
  • 18,301
  • 9
  • 84
  • 152
Prasanna Prasad
  • 253
  • 3
  • 8
  • 1
    You want to open iTunesLink which usually handled by safari which is not available in TVOS, you can test it by opening settings [[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]]; – Adnan Aftab Sep 20 '15 at 11:33
  • Anything come out of this? I have the same problem... – El Dude Dec 31 '15 at 03:10

1 Answers1

11

I assume you're wanting to test a Custom URL Scheme. You will want to use canOpenURL to see if the URL can be opened first. canOpenURL returns a BOOL value indicating whether or not the URL’s scheme can be handled by some app installed on the device. If canOpenURL returns YES then you would continue to open the URL with openURL.

YouTube links open the YouTube app by default on iOS devices. This behavior is not yet testable on the new Apple TV as YouTube's app is not accessible in the tvOS beta.

Here's an example of how to use canOpenURL to see if Facebook is installed on an iOS device using its Custom URL Scheme:

Obj-C:

// Check if FB app installed on device
if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"fb://"]]) {
   [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"fb://profile/355356557838717"]];
}
else {
   // FB not installed
   // Do something else
}

Swift:

// Check if FB app installed on device
if UIApplication.sharedApplication().canOpenURL(NSURL(string:"fb://")!) {
    UIApplication.sharedApplication().openURL(NSURL(string:"fb://profile/355356557838717")!)
}
else {
    // FB not installed
    // Do something else
} 

I'd anticipate that applications such as Facebook, and others, will implement their Custom URL Schemes in the same manner as their iOS counterparts.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Daniel Storm
  • 18,301
  • 9
  • 84
  • 152
  • Thank you.Is there a way any of this can be tested on the simulator? – Prasanna Prasad Sep 20 '15 at 12:17
  • 2
    @PrasannaPrasad Create an application and implement a Custom URL Scheme, ie. `ApplicationOne://`. Then create another application that opens the first application via the Custom URL Scheme you've declared. For example, `if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"ApplicationOne://"]])`. [Here's a nice screenshot](http://stackoverflow.com/a/32187854/2108547) of how to implement a Custom URL Scheme. – Daniel Storm Sep 20 '15 at 12:26
  • @DanielStorm Would you be able to cook up a Swift-based answer to this question? :) – esaruoho Jan 01 '16 at 19:35
  • @Hlung you need to use the Swift 3 syntax. – Daniel Storm Mar 25 '17 at 17:16