How to launch Safari and open URL from iOS app

Here’s what I did:

  1. I created an IBAction in the header .h files as follows:

     - (IBAction)openDaleDietrichDotCom:(id)sender;
    
  2. I added a UIButton on the Settings page containing the text that I want to link to.

  3. I connected the button to IBAction in File Owner appropriately.

  4. Then implement the following:

Objective-C

- (IBAction)openDaleDietrichDotCom:(id)sender {
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.daledietrich.com"]];
}

Swift

(IBAction in viewController, rather than header file)

if let link = URL(string: "https://yoursite.com") {
  UIApplication.shared.open(link)
}

Note that we do NOT need to escape string and/or address, like:

let myNormalString = "https://example.com";
let myEscapedString = myNormalString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed)!

In fact, escaping may cause opening to fail.

Leave a Comment