How to open Safari View Controller from a Webview (swift)
If I am understanding correctly you are loading a page on webview which has certain links now when user clicks on link you want to open those page in SVC. You can detect link click in webview using following delegate method and then open SVC from there.
EDIT
Based on edited question I can see that you are not calling showLinksClicked func , you can call this function as I have updated in following code and it should work.
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if navigationType == UIWebViewNavigationType.LinkClicked {
self.showLinksClicked()
return false
}
return true;
}
func showLinksClicked() {
let safariVC = SFSafariViewController(url: URL(string: "www.google.com")!)
present(safariVC, animated: true, completion: nil)
safariVC.delegate = self
}
func safariViewControllerDidFinish(controller: SFSafariViewController) {
controller.dismissViewControllerAnimated(true, completion: nil)
}
This piece of code will allow you to do this.
let safariVC = SFSafariViewController(URL: NSURL(string: "https://www.google.co.uk")!)
self.presentViewController(safariVC, animated: true, completion: nil)
safariVC.delegate = self
You may need to add this to the top of the class as well:
import SafariServices
Solution For Swift 4
Step 1:
import Safari Service In you Class
import SafariServices
Step 2:
Import SFSafariViewControllerDelegate in With your View Controller
class ViewController: UIViewController,SFSafariViewControllerDelegate {...}
Step 3:
Create A function to Open Safari View Controller.
func openSafariVC() {
let safariVC = SFSafariViewController(url: NSURL(string: "https://www.google.com")! as URL)
self.present(safariVC, animated: true, completion: nil)
safariVC.delegate = self
}
func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
controller.dismiss(animated: true, completion: nil)
}
Step 4:
call the function openSafariVC
openSafariVC()
Note: Don't forget To Add Navigation Controller with your View Controller.
Now your SafariVC is ready to open your Link within an app without Using UIWebView Oe WKWebView
For Swift 3:
First, import SafariServices and integrate the delegate into your class:
import SafariServices
class YourViewController: SFSafariViewControllerDelegate {
Then, to open Safari with the specified url:
let url = URL(string: "http://www,google.com")!
let controller = SFSafariViewController(url: url)
self.present(controller, animated: true, completion: nil)
controller.delegate = self
And now you can implement the delegate callback to dismiss safari when the user is finished:
func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
controller.dismiss(animated: true, completion: nil)
}