J. Doe
J. Doe

Reputation: 11

swift 3 open URLs in safari or native app

import UIKit
import WebKit


// Add WKWebView in StoryBoard
class ViewController: UIViewController {

    @IBOutlet var webView: WebView!

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        webView.loadUrl(string: "https://url.to/my/template")
    }
}

class WebView: WKWebView {

    required init?(coder: NSCoder) {

        if let _view = UIView(coder: coder) {
            super.init(frame: _view.frame, configuration: WKWebViewConfiguration())
            autoresizingMask = _view.autoresizingMask
        } else {
            return nil
        }
    }

    func loadUrl(string: String) {
        if let url = URL(string: string) {
            load(URLRequest(url: url))
        }
    }

}

The website is a html5 + CSS3. Purchased a template from themeforest but the developer said he doesn't offer support for xcode. As for now, all links are opening inside the webview. How can I open them in safari, and urls that go to apps, to open the installed apps, such as facebook, twitter? All I could find is to open ALL URLS in safari. L.E. Thank you! So I want to load the template hosted at the url, but the links within the template to load in safari, even better, like the answer with 3 votes from Swift Open Link in Safari. When I try to use that code, I get an error. Sorry and thanks! I don't know swift at all (or coding much).

Upvotes: 1

Views: 1696

Answers (1)

Lalit kumar
Lalit kumar

Reputation: 2207

If you want to open url as safari than You can use Add SafariSevices.Framework

 import SafariServices
 class ViewController: UIViewController, SFSafariViewControllerDelegate
 {

@IBAction func btnClick(_ sender: Any)

{
    let safariVC = SFSafariViewController(url: NSURL(string: "https://www.google.co.in") as! URL)

    self.present(safariVC, animated: true, completion: nil)

}

 func safariViewControllerDidFinish(controller: SFSafariViewController)
{
    controller.dismiss(animated: true, completion: nil)
}

}

Upvotes: 2

Related Questions