Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如果没有internet连接,则加载本地文件;函数一次又一次地调用自己_Ios_Swift_Webview_Reachability - Fatal编程技术网

Ios 如果没有internet连接,则加载本地文件;函数一次又一次地调用自己

Ios 如果没有internet连接,则加载本地文件;函数一次又一次地调用自己,ios,swift,webview,reachability,Ios,Swift,Webview,Reachability,这是我的代码,解释如下: func webViewDidStartLoad(homewebview: UIWebView) { if Reachability.isConnectedToNetwork() == true { print("Internet connection: OK") } else { print("Internet connection: FAILED") let path: String = NSBu

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

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连接时,它会打印
internet连接:OK

当没有internet连接时,它应该打印
internet连接:FAILED
,并打开
file.html

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

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


我怎样才能修好它?有人有主意吗?

在加载本地页面时,只需升起一个标志,即可跳过递归例程

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

        }
    }
}

加载本地文件仍会调用委托方法,因此在尝试加载本地文件时,您会看到没有网络连接,然后再次尝试加载。我自己也注意到了。我如何修复它?添加一个新的outlet:IBOutlet var checkInternetConnection:UIWebView难道不起作用吗然后
检查InternetConnection.loadRequest(请求)
?使用插座时没有区别,只是错误的可能性更大。为本地文件URL方案添加验证以防止无限循环。最后一句话是什么意思?你有一个例子吗?这是常见的方法吗?嗨,谢谢你的回答。似乎有效。非常感谢你。我对你的代码做了一点小改动。请批准。谢谢,谢谢你的帮助。非常聪明和简单的解决方案。