Search code examples
iosswiftwebviewuiwebviewpull-to-refresh

How do I add Pull to Refresh in WebView?


I'm very new to developing. I'm building a WebView and I want it to have pull to refresh capabilities. How do I go about doing that in swift?

My code in the View Controller is

@IBOutlet var webView: UIWebView!

override func viewDidLoad() {
    super.viewDidLoad()

    func webViewDidFinishLoad(webView: UIWebView) {
        UIApplication.sharedApplication().networkActivityIndicatorVisible = false
    }

    func webViewDidStartLoad(webView: UIWebView) {
        UIApplication.sharedApplication().networkActivityIndicatorVisible = true
    }

    let url = NSURL (string: "https://www.foo.com");
    let requestObj = NSURLRequest(URL: url!);
    webView.loadRequest(requestObj);
    NSUserDefaults.standardUserDefaults().registerDefaults(["UserAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/601.5.17 (KHTML, like Gecko) Version/9.1 Safari/601.5.17"])
}


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}

Solution

  • Your code is buggy you added two Web view Delegate in side the ViewDidLoad method that must be following and check the following viewDidLoad code for adding Pull to Refresh in web view:

    @IBOutlet var webView: UIWebView!
    
     var refController:UIRefreshControl = UIRefreshControl()
    
     override func viewDidLoad() {
        super.viewDidLoad()
    
    
        let url = NSURL (string: "https://www.foo.com");
        let requestObj = NSURLRequest(URL: url!);
        webView.loadRequest(requestObj);
        NSUserDefaults.standardUserDefaults().registerDefaults(["UserAgent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/601.5.17 (KHTML, like Gecko) Version/9.1 Safari/601.5.17"])
    
    
    
        refController.bounds = CGRectMake(0, 50, refController.bounds.size.width, refController.bounds.size.height) 
        refController.addTarget(self, action: Selector("mymethodforref:"), forControlEvents: UIControlEvents.ValueChanged)
        refController.attributedTitle = NSAttributedString(string: "Pull to refresh")
        webView.scrollView.addSubview(refController)
        }
    
    
    
        func mymethodforref(refresh:UIRefreshControl){
          webView.reload()
          refController.endRefreshing()
       }
        func webViewDidFinishLoad(webView: UIWebView) {
            UIApplication.sharedApplication().networkActivityIndicatorVisible = false
        }
    
        func webViewDidStartLoad(webView: UIWebView) {
            UIApplication.sharedApplication().networkActivityIndicatorVisible = true
        }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
    
        }
    
    }