Reputation: 21
As i implemented the code in which it perfectly work on Browser that is open the safari in ios and put myapp://
on address bar it open my app but i want when click on link which is inside UIWebView
@IBOutlet weak var webView: UIWebView!
override func viewDidLoad() {
super.viewDidLoad()
let setURL=URL(string:"https://myapp.com/")
let setURLRequest=URLRequest(url:setURL!)
webView.loadRequest(setURLRequest)
}
this is my code for loading website into webview and added URL TYPE >item0->myapp
item0->URL Scheme->myapp
when i add to link eg < a href="myapp://"></a>
it does not launch the another view getting errors
Appdelegate
public func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if request.url?.scheme == "myapp" {
// UIApplication.shared.open(request.url!, options: [:], //completionHandler: nil)
let myVC: MyAnotherController = MyAnotherController()
self.present(myVC, animated: true) { }
return false
}
return true
}
getting this error Value of type 'AppDelegate' has no member 'present'"
Upvotes: 1
Views: 3600
Reputation: 832
Use this code (It will work if the URL's last character contains "#"). "#" is added because if we navigate back to the last screen, it does not open.
link(www.google.com) in web view.
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest,
navigationType: UIWebViewNavigationType) -> Bool {
// request.url?.absoluteString = "www.google.com/#"
let last = request.url?.absoluteString.last
if last == "#" {
//do stuff here
}
return true
}
Upvotes: 0
Reputation: 1925
From inside if block, you need to return false, and it should work. By returning false the delegate method tells that the webView should not start loading the url.
public func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if request.url?.scheme == "myapp" {
// do your work here
UIApplication.shared.open(request.url!, options: [:], completionHandler: nil)
//Add the below line of code to the existing code
return false
}
return true
}
Upvotes: 2
Reputation: 19156
You can use UIWebView
delegate method optional public func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool
Example
public func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if request.url?.scheme == "myapp" {
// do your work here
UIApplication.shared.open(request.url, options: [:], completionHandler: nil)
}
return true
}
But you have to mention all the desire schemes in your app plist too..
Open other apps using url schemes
if let url = URL.init(string: "myapp://") {
if UIApplication.shared.canOpenURL(url) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
print("scheme is missing in info.plist or invalid scheme")
}
} else {
print("invalid url")
}
Upvotes: 2