Shane O'Seasnain
Shane O'Seasnain

Reputation: 3664

How to open a URL in Swift?

openURL has been deprecated in Swift 3.

Can anyone provide some examples of how the replacement openURL:options:completionHandler: works when trying to open a url?

Upvotes: 172

Views: 155181

Answers (6)

K.pen
K.pen

Reputation: 179

The open(_:options:) async method in iOS 10.0+ allows you to open a URL with additional options using Swift's async/await feature.

The open(_:options:) async -> Bool method is available in Swift 5.5 and later because it uses Swift's async/await feature, which was introduced with Swift 5.5 as part of Swift's concurrency model.

UIApplication.shared.open(websiteURL, completionHandler: nil)

Or

@available(iOS 10.0, *)
func openUniversalLink(_ url: URL) async {
    let options: [UIApplication.OpenExternalURLOptionsKey: Any] = [
        .universalLinksOnly: true
    ]
    
    let success = await UIApplication.shared.open(url, options: options)
    if success {
        print("Universal link opened successfully")
    } else {
        print("Failed to open universal link")
    }
}

Upvotes: 2

Nirav D
Nirav D

Reputation: 72410

Above answer is correct but if you want to check you canOpenUrl or not try like this.

let url = URL(string: "http://www.facebook.com")!
if UIApplication.shared.canOpenURL(url) {
    UIApplication.shared.open(url, options: [:], completionHandler: nil)
    //If you want handle the completion block than 
    UIApplication.shared.open(url, options: [:], completionHandler: { (success) in
         print("Open url : \(success)")
    })
}

Note: If you do not want to handle completion you can also write like this.

UIApplication.shared.open(url, options: [:])

No need to write completionHandler as it contains default value nil, check apple documentation for more detail.

Upvotes: 44

Scott Maretick
Scott Maretick

Reputation: 35

I'm using macOS Sierra (v10.12.1) Xcode v8.1 Swift 3.0.1 and here's what worked for me in ViewController.swift:

//
//  ViewController.swift
//  UIWebViewExample
//
//  Created by Scott Maretick on 1/2/17.
//  Copyright © 2017 Scott Maretick. All rights reserved.
//

import UIKit
import WebKit

class ViewController: UIViewController {

    //added this code
    @IBOutlet weak var webView: UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Your webView code goes here
        let url = URL(string: "https://www.google.com")
        if UIApplication.shared.canOpenURL(url!) {
            UIApplication.shared.open(url!, options: [:], completionHandler: nil)
            //If you want handle the completion block than
            UIApplication.shared.open(url!, options: [:], completionHandler: { (success) in
                print("Open url : \(success)")
            })
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


};

Upvotes: 3

Chetan Rajagiri
Chetan Rajagiri

Reputation: 1047

If you want to open inside the app itself instead of leaving the app you can import SafariServices and work it out.

import UIKit
import SafariServices

let url = URL(string: "https://www.google.com")
let vc = SFSafariViewController(url: url!)
present(vc, animated: true, completion: nil)

Upvotes: 41

Devran Cosmo Uenal
Devran Cosmo Uenal

Reputation: 6185

All you need is:

guard let url = URL(string: "http://www.google.com") else {
  return //be safe
}

if #available(iOS 10.0, *) {
    UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
    UIApplication.shared.openURL(url)
}

Upvotes: 421

Senõr Ganso
Senõr Ganso

Reputation: 1734

Swift 3 version

import UIKit

protocol PhoneCalling {
    func call(phoneNumber: String)
}

extension PhoneCalling {
    func call(phoneNumber: String) {
        let cleanNumber = phoneNumber.replacingOccurrences(of: " ", with: "").replacingOccurrences(of: "-", with: "")
        guard let number = URL(string: "telprompt://" + cleanNumber) else { return }

        UIApplication.shared.open(number, options: [:], completionHandler: nil)
    }
}

Upvotes: 8

Related Questions