Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pull to refresh not working in iOS WebView

I've implemented a straight forward WKWebView in iOS.

   var refreshControl = UIRefreshControl()
    refreshControl.addTarget(self, action: Selector("refreshWebView"), forControlEvents: UIControlEvents.ValueChanged)

This is in viewDidLoad()

And the corresponding refreshWebView function. But when I run it on mobile or simulator, no matter how much I drag, there is no pull to refresh action. Nothing is triggered, and it almost feels like I am stuck to the upper bounds of the screen. Where can be going wrong?

like image 630
RandomGuy Avatar asked Jul 02 '16 05:07

RandomGuy


2 Answers

Try to change your code like this, If you want to pull to refresh the webView you need to addSubView UIRefreshControl object in the ScrollView of webView like this

let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(self.refreshWebView(_:)), forControlEvents: UIControlEvents.ValueChanged)
webView.scrollView.addSubview(refreshControl)

Add func like this

func refreshWebView(sender: UIRefreshControl) {
    print("refersh")
    webView.loadRequest(NSURLRequest(URL: NSURL(string: "https://google.com")!))
    sender.endRefreshing()
}

Hope this will help you.

like image 85
Nirav D Avatar answered Oct 13 '22 19:10

Nirav D


SWIFT 4 Solution (Based on Nirav D answer)

You can simply call this setup method in your viewDidLoad:

private func setupRefreshControl() {
    let refreshControl = UIRefreshControl()
    refreshControl.addTarget(self, action: #selector(refreshWebView(sender:)), for: UIControlEvents.valueChanged)
    webView.scrollView.addSubview(refreshControl)
}

@objc
private func refreshWebView(sender: UIRefreshControl) {
    print("refreshing...")
    webView.load(URLRequest(url: url))
    sender.endRefreshing()
}
like image 30
Alessandro Francucci Avatar answered Oct 13 '22 18:10

Alessandro Francucci