Fabian Boulegue Fabian Boulegue - 3 months ago 20
iOS Question

Swift - Disable Links in WebView

I m currently looking for a way to disable Links in my WebView, this is my WebView

import UIKit

class ViewController_webView_news: UIViewController {
@IBOutlet weak var WebViewNews: UIWebView!
@IBOutlet weak var TBB_news: UITabBarItem!
@IBOutlet weak var activity: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()

var TBB_news_img = UIImage(named: "TabbarNews.png") as UIImage
TBB_news.selectedImage = TBB_news_img
var newsurl = "http://google.com"
let newsViewUrl = NSURL(string: newsurl)
let request = NSURLRequest(URL: newsViewUrl)
WebViewNews.loadRequest(request)




}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()

}
@IBAction func BThome(sender: AnyObject) {

var newsurl = "http://google.com"
let newsViewUrl = NSURL(string: newsurl)
let request = NSURLRequest(URL: newsViewUrl)
WebViewNews.loadRequest(request)
}
func webViewDidStartLoad(_ : UIWebView){activity.startAnimating()
}
func webViewDidFinishLoad(_ : UIWebView){activity.stopAnimating()}


Is there a way to use "UIWebViewNavigationType.LinkClicked" for this?
Currently i m using

let result = WebViewNews.stringByEvaluatingJavaScriptFromString("window.location.href = \"http://google.de\";")

Answer

Use UIWebViewDelegate method and set it return to NO always. this way it will never load any other url. This is objective c code you need change it to swift.

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    return NO;
}

For swift read here

Swift:

func webView(WebViewNews: UIWebView!, shouldStartLoadWithRequest request: NSURLRequest!, navigationType: UIWebViewNavigationType) -> Bool {
return false;
}
Comments