Swift: How to open a new app when UIButton is tapped

I have an app and when a uibutton is clicked, I want to open another app that is already installed (i.e. Waze). How can I do such? Big thanks.


Try this. For example you want to open an Instagram app:

let instagramHooks = "instagram://user?username=johndoe"
let instagramUrl = URL(string: instagramHooks)!
if UIApplication.shared.canOpenURL(instagramUrl)
{  
    UIApplication.shared.open(instagramUrl)
} else {
    //redirect to safari because the user doesn't have Instagram
    UIApplication.shared.open(URL(string: "http://instagram.com/")!)
}

In SecondApp

Go to the plist file of SecondApp and you need to add a URL Schemes with a string iOSDevTips(of course you can write another string.it's up to you).

enter image description here

2 . In FirstApp

Create a button with the below action:

- (void)buttonPressed:(UIButton *)button
{
  NSString *customURL = @"iOSDevTips://";

  if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:customURL]])
  {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:customURL]];
  }
  else
  {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"URL error"
                              message:[NSString stringWithFormat:@"No custom URL defined for %@", customURL]
                              delegate:self cancelButtonTitle:@"Ok" 
                              otherButtonTitles:nil];
    [alert show];
  }

}

That's it. Now when you can click the button in the FirstApp it should open the SecondApp.

For more info Refer here


You can look up Waze Community for reference.

Objective-C code snippet:

if ([[UIApplication sharedApplication]
canOpenURL:[NSURL URLWithString:@"waze://"]]) {

  // Waze is installed. Launch Waze and start navigation
  NSString *urlStr =
    [NSString stringWithFormat:@"waze://?ll=%f,%f&navigate=yes",
    latitude, longitude];

  [[UIApplication sharedApplication] openURL:[NSURL URLWithString:urlStr]];

 } else {

  // Waze is not installed. Launch AppStore to install Waze app
  [[UIApplication sharedApplication] openURL:[NSURL
    URLWithString:@"http://itunes.apple.com/us/app/id323229106"]];
}

Swift code snippet:

if UIApplication.shared.canOpenURL(URL(string: "waze://")!) {
    // Waze is installed. Launch Waze and start navigation
    let urlStr = String(format: "waze://?ll=%f, %f&navigate=yes", latitude, longitude)
    UIApplication.shared.openURL(URL(string: urlStr)!)
} else {
    // Waze is not installed. Launch AppStore to install Waze app
    UIApplication.shared.openURL(URL(string: "http://itunes.apple.com/us/app/id323229106")!)
}

In Swift 4 you can use:

if let url = URL(string: "\(myUrl)") {
    UIApplication.shared.open(url, options: [:], completionHandler: nil)
}