【问题标题】:Load local file if no internet connection; function calls itself again and again如果没有互联网连接,则加载本地文件;函数一次又一次地调用自己
【发布时间】:2016-07-08 15:00:08
【问题描述】:

这是我的代码,解释如下:

func webViewDidStartLoad(homewebview: UIWebView) {

    if Reachability.isConnectedToNetwork() == true {
        print("Internet connection: OK")

    } else {
        print("Internet connection: FAILED")

        let path: String = NSBundle.mainBundle().pathForResource("file", ofType: "html")!
        let url: NSURL = NSURL.fileURLWithPath(path)
        let request: NSURLRequest = NSURLRequest(URL: url)
        homewebview.loadRequest(request)
    }
}

点击超链接时webViewDidStartLoad会被调用。

当有互联网连接时,它会打印Internet connection: OK

当没有互联网连接时,它应该打印Internet connection: FAILED并打开file.html

但是当打开本地文件时,它会一遍又一遍地调用整个函数……就像一个永无止境的循环。

我想在单击 WebView 中的(超)链接时检查互联网连接。如果没有 Internet 连接,则应在此 WebView 中加载本地文件,而无需再次调用该函数。

我该如何解决?有人有想法吗?

【问题讨论】:

  • 加载本地文件仍然调用委托方法,所以你看到在尝试加载本地文件时没有网络连接,然后再次尝试加载。
  • 我自己也注意到了。我该如何解决?
  • 不应该添加一个新的插座:@IBOutlet var checkInternetConnection: UIWebView! 然后checkInternetConnection.loadRequest(request)
  • 使用插座没有区别,只是更容易出错。添加对本地文件 URL 方案的验证以防止无限循环。
  • 最后一句话是什么意思?你有一个例子吗?这是常见的方法吗?

标签: ios swift webview reachability


【解决方案1】:

在加载本地页面时只需升旗即可跳过递归例程。

var loadingLoacalPage = false
//..//
func webViewDidStartLoad(homewebview: UIWebView) {
        if Reachability.isConnectedToNetwork() == true {
            print("Internet connection: OK")

        } else {
            print("Internet connection: FAILED")

            let alert = UIAlertView(title: "No internet connection", message: "Check internet connection.", delegate: nil, cancelButtonTitle: "Okay")
            alert.show()

            if(!loadingLoacalPage){

            let path: String = NSBundle.mainBundle().pathForResource("file", ofType: "html")!
            let url: NSURL = NSURL.fileURLWithPath(path)
            let request: NSURLRequest = NSURLRequest(URL: url)
            homewebview.loadRequest(request)

            loadingLoacalPage = true

        }
    }
}

【讨论】:

  • 您好,感谢您的回答。似乎工作。非常感谢你。我对你的代码做了一个小改动。请批准。
  • 谢谢你,也谢谢你的帮助。非常聪明和简单的解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-01
  • 1970-01-01
相关资源
最近更新 更多