Reputation: 2303
I am loading some content from the web into a UIWebView
, but I'd like all links to be disabled in the UIWebView
. Is this possible? I could parse the text, but I'm looking for something easier.
Upvotes: 19
Views: 17827
Reputation: 1828
Tested in Swift 4.0: This approach doesn't involve having an extra variable to test if this is the initial load or not. Simply check the type of request (in this case, LinkClicked) and return false in that case. Otherwise simply return true!
(Of course make sure you set the webView.delegate
)
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if navigationType == .linkClicked {
return false
}
return true
}
Upvotes: 11
Reputation: 295
Another answer for Swift 3.0 :
Just give zero for don't detect any type link of yourWebView initial code
yourWebView.dataDetectorTypes = UIDataDetectorTypes(rawValue: 0)
Upvotes: 1
Reputation: 39
For swift 3:
Try removing the types you don't want to show as link from webView.dataDetectorTypes
webView.dataDetectorTypes.remove(UIDataDetectorTypes.all)
Upvotes: 1
Reputation: 732
I had a similar need and for some cases just using the webViewDidFinishLoad was not enough, so I used the webViewDidStartLoad to cover all cases:
func webViewDidStartLoad(webView: UIWebView) {
startedLoading = true
}
func webViewDidFinishLoad(webView: UIWebView) {
alreadyOpen = true
}
func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if startedLoading && alreadyOpen {
// do something
return false
}else if startedLoading && !alreadyOpen{
return false
}else if !startedLoading {
return true
}
return true
}
In some cases when the html was loaded but some resources, like images and some heavy assets inside the DOM were not the didFinishLoad method was not fired and the user could navigate in this "short" interval.
Upvotes: 0
Reputation: 535
Simple answer that works in Swift 2.0:
yourWebView.dataDetectorTypes = UIDataDetectorTypes.None
Just implement it in the view controller where you are defining and using your web view and it will work flawlessly.
Upvotes: 0
Reputation: 243146
You can give the UIWebView
a delegate and implement the -webView:shouldStartLoadWithRequest:navigationType:
delegate method to return NO;
(except on the initial load).
That will prevent the user from viewing anything but that single page.
To provide an example requested in the comments... Start with allowLoad=YES
and then:
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
return allowLoad;
}
- (void)webViewDidFinishLoad:(UIWebView*)webView {
allowLoad = NO;
}
Upvotes: 54
Reputation: 3809
You can disable data detect from your webview.
[webView setDataDetectorTypes:UIDataDetectorTypeNone];
Upvotes: 4