Search code examples
javascriptiosswiftrefresh

Why do not working UIRefreshControl in Swift?


I use the refresh function in WKWebview. The function is normal when performing a refresh. But when I load another html file and come back, it is not refreshed.

@IBOutlet var myWebView: WKWebView!
var refController:UIRefreshControl = UIRefreshControl()

override func viewDidLoad() {
    super.viewDidLoad()
    myWebView.uiDelegate = self
    myWebView.navigationDelegate = self
    myWebView.scrollView.delegate = self
    refController.bounds = CGRect.init(x: 0.0, y: 50.0, width: refController.bounds.size.width, height: refController.bounds.size.height)
    refController.addTarget(self, action: #selector(self.webviewRefresh(refresh:)), for: .valueChanged)
    myWebView.scrollView.addSubview(refController)
    ...
}

@objc func webviewRefresh(refresh:UIRefreshControl){
    refController.endRefreshing()
    myWebView.reload()
}

extension mainWebViewController: UIScrollViewDelegate{
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        print("come in ??")
        if currentHtmlFileName == "Main.html" {
            scrollView.bounces = (scrollView.contentOffset.y <= 0)
        } else {
            scrollView.bounces = false
        }
    }
}

As you can see from my code, my WKWebview is scrolling, and the function is executed. However, when the function is activated on a different screen and returned, the function is not called, nor is the refresh working.

The steps for reproducing a problem are as follows:

  1. Load the WKwebView page and execute the refresh function.
  2. Scroll to the bottom screen to see if there is a bounce.
  3. If it works normally, go to a different screen. location.href = "./other.html";
  4. Scroll from another screen to the bottom screen to see if there is a bounce.
  5. If there is no bounce normally, please return to the screen. history.back()
  6. And run the refresh function again.

In my case, I have a bounce, but the refresh does not run, and the function is not called.

Has anyone solved the same problem as me? Is this a bug???


Solution

  • I thought a lot about this problem. So my conclusion is history.back() does not change the value of the bounce. Therefore, the bounce value is false.

    So I thought I should reinitialize this value. So I added a function in the section that completes page navigation.

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
         if currentHtmlFileName == "Main.html" {
             scrollViewDidScroll(myWebView.scrollView)
         }
    }
    

    With this addition, the bounce value was reinitialized, and my refresh worked.