0

Trying to achieve the option to refresh the WebView URL with no success, so far I have this

class ViewController2: UIViewController {

@IBOutlet var webview2: WKWebView!

override func viewDidLoad() {
    super.viewDidLoad()
    webview2.load(URLRequest(url: URL(string: "https://coinmarketcap.com/")!))
    
}


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

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

Someone can tell me why it doesn't work? I'm new on this

1 Answers1

0

After realizing some mistakes I made, I found the solution. The correct code to refresh the WebView is:

class ViewController2: UIViewController {

@IBOutlet var webview2: WKWebView!
@objc let refreshControl = UIRefreshControl()

override func viewDidLoad() {
    super.viewDidLoad()
    webview2.load(URLRequest(url: URL(string: "https://coinmarketcap.com/")!))
    
    webview2.scrollView.bounces = true
    let refreshControl = UIRefreshControl()
    refreshControl.addTarget(self, action: #selector(ViewController2.refreshWebView), for: UIControl.Event.valueChanged)
    webview2.scrollView.addSubview(refreshControl)
}

@objc func refreshWebView(sender: UIRefreshControl) {
    webview2.load(URLRequest(url: URL(string: "https://coinmarketcap.com/")!))
    sender.endRefreshing()
}
}