Remove context menu from the swift 4.0 webview - ios

I want to disable the context menu ie any action to maintain an element of my WKWebView swift 4
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate {
var webView: WKWebView!
override func loadView() {
webView = WKWebView()
webView.navigationDelegate = self
view = webView
}
override func viewDidLoad() {
super.viewDidLoad()
// 1
let url = URL(string: "https://www.google.com")!
webView.load(URLRequest(url: url))
// 2
let refresh = UIBarButtonItem(barButtonSystemItem: .refresh, target: webView, action: #selector(webView.reload))
toolbarItems = [refresh]
navigationController?.isToolbarHidden = false
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
title = webView.title
}
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
//show progress indicator
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
//show error
}
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
//show error
}
private weak var lastPresentedController : UIViewController?
override func dismiss(animated flag: Bool, completion: (() -> Void)? = nil) {
// WKWebView actions sheets workaround
if presentedViewController != nil && lastPresentedController != presentedViewController {
lastPresentedController = presentedViewController;
presentedViewController?.dismiss(animated: flag, completion: {
completion?();
self.lastPresentedController = nil;
});
} else if lastPresentedController == nil {
super.dismiss(animated: flag, completion: completion);
}
}
}

Related

Webview Back & Forward Button Not working (Swift, Xcode 14)

My webView Back & Forward buttons used to work but they are not anymore. I've looked everywhere I could for a solution but only found similar ones including here but nothing works for me or for Swift (at least to me). Below are my codes.I have Webkit Framework added, still not working when the buttons did work before even without adding the Framework. App Transport Security setting is set to YES for Arbitrary Load as before when the buttons were working. Did Apple change something? Please help. Thanks!!!
import UIKit
import WebKit
class SocialPlatformController: UIViewController, WKNavigationDelegate {
#IBOutlet weak var BackBtn: UIButton!
#IBOutlet weak var ForwardBtn: UIButton!
#IBOutlet weak var webView: WKWebView!
#IBAction func backToMainScreen(_ sender: Any) {
}
#IBAction func goBackBtnTap(_ sender: Any) {
if webView.canGoBack {
webView.goBack()
}
}
#IBAction func goForwardBtnTap(_ sender: Any) {
if webView.canGoForward {
webView.goForward()
}
}
func webView(_ webView: WKWebView, decidePolicyFor navigationResponse: WKNavigationResponse, decisionHandler: #escaping (WKNavigationResponsePolicy) -> Swift.Void) {
BackBtn.isEnabled = webView.canGoBack
ForwardBtn.isEnabled = webView.canGoForward
guard
let response = navigationResponse.response as? HTTPURLResponse,
let url = navigationResponse.response.url
else {
decisionHandler(.cancel)
return
}
if let headerFields = response.allHeaderFields as? [String: String] {
let cookies = HTTPCookie.cookies(withResponseHeaderFields: headerFields, for: url)
cookies.forEach { (cookie) in
HTTPCookieStorage.shared.setCookie(cookie)
}
}
decisionHandler(.allow)
}
override func viewDidLoad() {
super.viewDidLoad()
webView.navigationDelegate = self
let url:URL = URL(string:"https://www.facebook.com/groups/246328283932460")!
let urlRequest:URLRequest = URLRequest(url: url)
webView.load(urlRequest)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override public func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
}
Perhaps it's better to handle the Back and Forward button state in a navigation delegate handler that's fired after the navigation has been finished, for example:
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!)
//successful load
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
updateButtons()
}
//failure load
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
updateButtons()
}
//back-forward button update
func updateButtons() {
backButton.isEnabled = webView.canGoBack
forwardbutton.isEnabled = webView.canGoForward
}
You can follow these delegates and methods. I think buttons are not getting updated/loaded as they should.

how to hide html elements in wkwebview in IOS?

i want to hide certain html elements in wkwebview using swift 4, xcode 9. i know how to do it in android and have added the code below. i just need an equivalent code for ios in swift 4 for wkwebView.
myWebView.setWebViewClient(new WebViewClient()
{
#Override
public void onPageFinished(WebView view, String url)
{
myWebView.loadUrl("javascript:(function() { " +
"document.getElementById('divHeader')
[0].style.display='none'; " +
"})()");
}
});
myWebView.loadUrl(URL);
Use WKWebView
import WebKit
class FirstViewController: UIViewController, WKNavigationDelegate {
#IBOutlet weak var webVw: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
webVw.navigationDelegate = self
loadmyPage(htmlstr: "https://www.mywebsite.com")
}
func loadmyPage(htmlstr:String){
let url = URL (string: htmlstr)
let request = URLRequest(url: url!)
webVw.load(request)
}
//MARK:- WKNavigationDelegate
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
print(error.localizedDescription)
}
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
print("Start to load")
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print("finish to load")
let elementID = "right_sidebar"
let removeElementIdScript = "var element = document.getElementById('\(elementID)'); element.parentElement.removeChild(element);"
webView.evaluateJavaScript(removeElementIdScript) { (response, error) in
debugPrint("Am here")
}
}

create activity indicator when navigate in webView using webkit in swift 4

I want to create a wkwebview in my iOS app, and I want to add an activity indicator to it. I want when we click all the button or part in the webview, it will appear the activity indicator. Can you give me some code to do this? Here's my code right now. It only show the indicator when start load the website but when we click at the process, the indicator not appear.
import UIKit
import WebKit
class ViewController: UIViewController,WKNavigationDelegate,UIWebViewDelegate {
#IBOutlet weak var activityIndicator: UIActivityIndicatorView!
#IBOutlet weak var webView: WKWebView!
#IBOutlet var containerView: UIView? = nil
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(self.activityIndicator)
self.view.addSubview(self.webView)
let url:URL = URL(string : "https://www.facebook.com/")!
let urlRequest : URLRequest = URLRequest(url: url)
webView.load(urlRequest)
//activity indicator
self.webView.addSubview(self.activityIndicator)
self.activityIndicator.startAnimating()
self.webView.navigationDelegate = self
self.activityIndicator.hidesWhenStopped = true
//refresh
webView.scrollView.bounces = true
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(ViewController.refreshWebView), for: UIControlEvents.valueChanged)
webView.scrollView.addSubview(refreshControl)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear( animated )
let url:URL = URL(string : "https://www.facebook.com/")!
let urlRequest : URLRequest = URLRequest(url: url)
webView.load(urlRequest)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
activityIndicator.stopAnimating()
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
activityIndicator.stopAnimating()
}
#objc func refreshWebView(sender: UIRefreshControl) {
print("refersh")
sender.endRefreshing()
}
}
Below code will help to add activity indicator in Navigation Bar. So no need to create any subviews. This works with Swift 4.
import Foundation
import UIKit
import WebKit
class ContactVC: UIViewController, WKNavigationDelegate {
var webView: WKWebView!
var activityIndicator: UIActivityIndicatorView!
override func loadView() {
webView = WKWebView()
webView.navigationDelegate = self
view = webView
activityIndicator = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
activityIndicator.hidesWhenStopped = true
let barButton = UIBarButtonItem(customView: activityIndicator)
self.navigationItem.setRightBarButton(barButton, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
let url = URL(string: "https://www.facebook.com/")!
webView.load(URLRequest(url: url))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func showActivityIndicator(show: Bool) {
if show {
// Start the loading animation
activityIndicator.startAnimating()
} else {
// Stop the loading animation
activityIndicator.stopAnimating()
}
}
//MARK:- WKNavigationDelegate
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
print("Start to load")
showActivityIndicator(show: true)
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
print("Finish to load")
title = webView.title
showActivityIndicator(show: false)
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
print(error.localizedDescription)
showActivityIndicator(show: false)
}
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
print(error.localizedDescription)
showActivityIndicator(show: false)
}
}
Implement didStartProvisionalNavigation delegate function.
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
activityIndicator.startAnimating()
}

How to add Activity Indicator to WKWebView (Swift 3)

I have a wkwebview in my app, and I want to add an activity indicator to it. I want it to where it appears when the webview is loading and disappears whenever it is finished loading, it disappears. Can you give me some code to do this? Here's my code right now:
#IBOutlet weak var Activity: UIActivityIndicatorView!
var webView : WKWebView!
#IBOutlet var containerView: UIView? = nil
override func viewDidLoad() {
super.viewDidLoad()
guard let url = URL(string: "http://ifunnyvlogger.wixsite.com/ifunnyvlogger/app-twitter") else { return }
webView = WKWebView(frame: self.view.frame)
webView.translatesAutoresizingMaskIntoConstraints = false
webView.isUserInteractionEnabled = true
webView.navigationDelegate = self
self.view.addSubview(self.webView)
let request = URLRequest(url: url)
webView.load(request)
}
func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: #escaping (WKNavigationActionPolicy) -> Void) {
// Check if a link was clicked
if navigationAction.navigationType == .linkActivated {
// Verify the url
guard let url = navigationAction.request.url else { return }
let shared = UIApplication.shared
// Check if opening in Safari is allowd
if shared.canOpenURL(url) {
// Ask the user if they would like to open link in Safari
let alert = UIAlertController(title: "Do you want to open Safari?", message: nil, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Yes", style: .default, handler: { (alert: UIAlertAction) -> Void in
// User wants to open in Safari
shared.open(url, options: [:], completionHandler: nil)
}))
alert.addAction(UIAlertAction(title: "Opps, no.", style: .cancel, handler: nil))
present(alert, animated: true, completion: nil)
}
decisionHandler(.cancel)
}
decisionHandler(.allow)
}
func webViewDidStartLoad(_ : WKWebView) {
Activity.startAnimating()
}
func webViewDidFinishLoad(_ : WKWebView) {
Activity.startAnimating()
}
I'm creating an IOS app using xcode 8 and swift 3
Please, below code which is working fine.
#IBOutlet weak var Activity: UIActivityIndicatorView!
var webView : WKWebView!
#IBOutlet var containerView: UIView? = nil
override func viewDidLoad() {
super.viewDidLoad()
guard let url = URL(string: "http://www.facebook.com") else { return }
webView = WKWebView(frame: self.view.frame)
webView.translatesAutoresizingMaskIntoConstraints = false
webView.isUserInteractionEnabled = true
self.view.addSubview(self.webView)
let request = URLRequest(url: url)
webView.load(request)
// add activity
self.webView.addSubview(self.Activity)
self.Activity.startAnimating()
self.webView.navigationDelegate = self
self.Activity.hidesWhenStopped = true
}
Implement below these two delegate method:
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
Activity.stopAnimating()
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
Activity.stopAnimating()
}
Let me know if it is not working.
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate, WKUIDelegate {
var webView: WKWebView!
var activityIndicator: UIActivityIndicatorView!
override func viewDidLoad() {
webView = WKWebView(frame: CGRect.zero)
webView.navigationDelegate = self
webView.uiDelegate = self
view.addSubview(webView)
activityIndicator = UIActivityIndicatorView()
activityIndicator.center = self.view.center
activityIndicator.hidesWhenStopped = true
activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.gray
view.addSubview(activityIndicator)
webView.load(URLRequest(url: URL(string: "http://google.com")!))
}
func showActivityIndicator(show: Bool) {
if show {
activityIndicator.startAnimating()
} else {
activityIndicator.stopAnimating()
}
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
showActivityIndicator(show: false)
}
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
showActivityIndicator(show: true)
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
showActivityIndicator(show: false)
}
}
Swift 5 Version
The concept is simple enough to be ported to earlier swift versions.
This is a class we would use as a parent class anywhere we want a webview.
import UIKit
import WebKit
class CustomWebViewController: UIViewController, WKNavigationDelegate {
var activityIndicator: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
activityIndicator = UIActivityIndicatorView()
activityIndicator.center = self.view.center
activityIndicator.hidesWhenStopped = true
activityIndicator.style = .gray
activityIndicator.isHidden = true
view.addSubview(activityIndicator)
}
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
activityIndicator.isHidden = false
activityIndicator.startAnimating()
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
activityIndicator.stopAnimating()
activityIndicator.isHidden = true
}
}
If we have a UIViewController with a webview, we can just inherit from CustomWebViewController and it will take care of the rest for us. Remember to connect the webview IBOutlet.
import UIKit
import WebKit
class FirstViewController: CustomWebViewController {
#IBOutlet var webView: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()
webView.navigationDelegate = self
let url = URL(string: "https://google.com")
webView.load(URLRequest(url: url!))
}
}
In viewDidLoad you need to add the activityIndicator as a subView just as you did for your webView. Since it's an outlet, make sure the activityIndicator sits on top of your webView and you should be good to go. You also want to set activity.hidden to true when the webView stops loading.
It's also a good rule of thumb to lower case your 'Activity' outlet.
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(self.Activity)
guard let url = URL(string: "http://ifunnyvlogger.wixsite.com/ifunnyvlogger/app-twitter") else { return }
webView = WKWebView(frame: self.view.frame)
webView.translatesAutoresizingMaskIntoConstraints = false
webView.isUserInteractionEnabled = true
webView.navigationDelegate = self
self.view.addSubview(self.webView)
let request = URLRequest(url: url)
webView.load(request)
You also call activity.startAnimating in webViewDidFinishLoad(). Make sure you call activity.stopAnimating() when the webView finishes loading. Happy coding!
func webViewDidFinishLoad(_ : WKWebView) {
Activity.stopAnimating()
Activity.hidden = true
}
import UIKit
import WebKit
class ViewController: UIViewController, WKNavigationDelegate, WKUIDelegate {
var webView: WKWebView!
var activityIndicator: UIActivityIndicatorView!
override func viewDidLoad() {
webView = WKWebView(frame: CGRect.zero)
webView.navigationDelegate = self;
webView.uiDelegate = self
activityIndicator = UIActivityIndicatorView()
activityIndicator.hidesWhenStopped = true
activityIndicator.center = self.view.center
activityIndicator.style = UIActivityIndicatorView.Style.large
webView.addSubview(activityIndicator)
view = webView
let load_url = URL(string: "https://google.com/")!
webView.load(URLRequest(url: load_url))
activityIndicator.startAnimating()
let refresh = UIBarButtonItem(barButtonSystemItem: .refresh, target: webView, action: #selector(webView.reload))
toolbarItems = [refresh]
navigationController?.isToolbarHidden = false
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
title = webView.title
activityIndicator.stopAnimating()
}
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
activityIndicator.startAnimating()
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
activityIndicator.stopAnimating()
}
}
Please try the below code its working fine for me and please let me know if anything is wrong in it thanks in advance.
import UIKit
import WebKit
class WebViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {
#IBOutlet weak var contentView: UIView!
#IBOutlet weak var activityIndicatorView: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
setupView()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
self.setupWebView()
self.loadData()
}
fileprivate func setupView() {
self.contentView.isHidden = true
self.activityIndicatorView.startAnimating()
}
fileprivate func setupWebView() {
let webConfiguration = WKWebViewConfiguration()
webView = WKWebView(frame: contentView.bounds, configuration: webConfiguration)
webView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.contentView.addSubview(webView)
self.webView.allowsBackForwardNavigationGestures = true
webView.uiDelegate = self
webView.navigationDelegate = self
}
fileprivate func loadData() {
if let url = URL(string: "http://google.com") {
/// For loading PDF content
if contentType == .pdf {
if let data = try? Data(contentsOf: url) {
self.webView.load(data, mimeType: "application/pdf", characterEncodingName: "", baseURL: url)
}
} else {
let request = URLRequest(url: url)
webView.load(request)
}
}
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
activityIndicatorView.stopAnimating()
self.contentView.isHidden = false
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
activityIndicatorView.stopAnimating()
}
}

Activity Indicator won't stop spinning after WKWebView load finish

I am very new to Swift and iOS development so thank you so much in advance for helping me!
I have tried every example online and every page on this site and I cannot get my Activity Indicator to stop being displayed once the page completes loading in my WKWebview.
Any assistance would be so appreciated! Thank you!
import UIKit
import WebKit
class FirstViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {
#IBOutlet var webView: WKWebView!
#IBOutlet var activityIndicator: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
webView.uiDelegate = self
activityIndicator.startAnimating()
activityIndicator.isHidden = true
activityIndicator.hidesWhenStopped = true
let url = Bundle.main.url(forResource: "Web/bulk_material_table", withExtension: "html")!
webView.loadFileURL(url, allowingReadAccessTo: url)
let request = URLRequest(url: url)
self.webView.load(request)
}
func showActivityIndicator(show: Bool) {
if show {
activityIndicator.startAnimating()
} else {
activityIndicator.stopAnimating()
}
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
showActivityIndicator(show: false)
}
func webView(_ webView: WKWebView, didStartProvisionalNavigation navigation: WKNavigation!) {
showActivityIndicator(show: true)
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
showActivityIndicator(show: false)
}
}
Just replace
webView.uiDelegate = self
with
webView.navigationDelegate = self
And it will work because
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
showActivityIndicator(show: false)
}
is WKNavigationDelegate's delegate method.

Resources