Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pull to refresh on UIWebView?

I'm trying to make a pull to refresh on a UIWebView that I load a website. The code of the UIWebView is pretty simple

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var WebView: UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let URL = NSURL(string: "https://the url/")

        WebView.loadRequest(NSURLRequest(URL: URL!))

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }    
}

Does anyone have any example because no matter what I search I only found pull to refresh on tableviews and I'm not sure if it will work with this one too.

Thanks.

Update 1. After the suggestion of Sohil the code is like this

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var WebView: UIWebView!
    @IBOutlet weak var scrollView: UIScrollView!
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.

        let URL = NSURL(string: "https://iremember.gr/")

        WebView.loadRequest(NSURLRequest(URL: URL!))
    }




    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
        func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {

            if (scrollView.contentOffset.y < 0){
                //reach top
                print("Reach Top")
                WebView.reload()
            }
            else {
                print("nothing")
            }
        }
    }

}

But it doesnt even print "nothing" when I try to reload it.

like image 961
Konstantinos Natsios Avatar asked Nov 30 '15 10:11

Konstantinos Natsios


1 Answers

You can use the UIScrollView to achieve that task. Firstly, you need to check whether user is pulling the UIWebView 'Up' or 'Down', for that below code will help view and then reload the UIWebView:

func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {

     if (scrollView.contentOffset.y < 0){
     //reach top
          print("Reach Top")
          webView.reload()
     }
 }

Make sure you have added the delegate to UIScrollView:

webView.scrollView.delegate = self

Hope this helps!

like image 150
Sohil R. Memon Avatar answered Sep 28 '22 00:09

Sohil R. Memon