Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I launch Safari from an iPhone app?

Tags:

ios

safari

launch

should be the following :

NSURL *url = [NSURL URLWithString:@"http://www.stackoverflow.com"];

if (![[UIApplication sharedApplication] openURL:url]) {
    NSLog(@"%@%@",@"Failed to open url:",[url description]);
}

UIApplication has a method called openURL:

example:

NSURL *url = [NSURL URLWithString:@"http://www.stackoverflow.com"];

if (![[UIApplication sharedApplication] openURL:url]) {
  NSLog(@"%@%@",@"Failed to open url:",[url description]);
}

you can open the url in safari with this:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://www.google.com"]];

With iOS 10 we have one different method with completion handler:

ObjectiveC:

NSDictionary *options = [NSDictionary new];
//options can be empty
NSURL *url = [NSURL URLWithString:@"http://www.stackoverflow.com"];
[[UIApplication sharedApplication] openURL:url options:options completionHandler:^(BOOL success){
}];

Swift:

let url = URL(string: "http://www.stackoverflow.com")
UIApplication.shared.open(url, options: [:]) { (success) in
}

Maybe someone can use the Swift version:

In swift 2.2:

UIApplication.sharedApplication().openURL(NSURL(string: "https://www.google.com")!)

And 3.0:

UIApplication.shared().openURL(URL(string: "https://www.google.com")!)

In swift 4 and 5, as OpenURL is depreciated, an easy way of doing it would be just

if let url = URL(string: "https://stackoverflow.com") {
    UIApplication.shared.open(url, options: [:]) 
}

You can also use SafariServices. Something like a Safari window within your app.

import SafariServices

...

if let url = URL(string: "https://stackoverflow.com") {
    let safariViewController = SFSafariViewController(url: url)        
    self.present(safariViewController, animated: true)
}