1

当应用程序首次打开时,我使用此代码检查互联网:

//No Internet Connection error code
-(void)webView:(UIWebView *)webVIEW didFailLoadWithError:(NSError *)error {
     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No Internet Connection!" message:@"In order to use this app you need an active Internet connection!" delegate:self cancelButtonTitle:@"Close" otherButtonTitles:nil, nil];
   [alert show];  
}

//Close app from Alert View
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
exit(0);
}

我有一个具有 jQuery .click() 函数的 UIWebView 应用程序。一旦用户单击该按钮,有没有办法再次检查 Internet?

4

4 回答 4

1

如果您使用 Apple 的可达性代码或类似代码,那么您需要该currentReachabilityStatus方法;否则调用底层SCNetworkReachabilityGetFlags函数

于 2012-09-02T14:16:25.917 回答
1

请记住,单击不一定通过网络连接请求更多资源。

UIWebViewDelegate有一个webView:shouldStartLoadWithRequest:navigationType选择器,它将成为你的朋友。要随时触发它(点击或其他操作),请将隐藏 iframe 的源设置为某个虚拟值,并在您的委托方法中检查该值(这将运行您的测试并返回NO.

我建议在没有连接时不要退出,因为用户可能会将其视为崩溃,特别是如果他们的连接丢失只是暂时的(通过隧道)。此外,重复测试连接可能会不必要地减慢您的应用程序,并为用户产生更多的数据费用。

于 2012-09-01T15:01:46.443 回答
1

你可以这样做:

在函数 click() 中,您应该添加以下代码:

window.location = "fake://myApp/checkForInternet";

在你的 Objective-C 代码中添加这个:

-(BOOL) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString *link = request.URL.absoluteString;

    if ([link isEqualToString:@"fake://myApp/checkForInternet"])
    {
            // check for Reachability here
        return NO;
    }

    return YES;
}

请注意,在此示例中 -webView:shouldStartLoad... 在 webView 中的每个事件仅调用一次。如果您想在一个事件中在一个 JavaScript 函数中检查两次或更多次,我可以提供更复杂的代码

正如@Rajneesh071 所说,在 Apple 文档中或这里是 GitHub 上的项目中阅读有关检查可达性的信息

于 2012-09-01T15:08:06.600 回答
1

看一下 Apple 的示例代码。Reachability 项目展示了如何检测连接

http://developer.apple.com/iphone/library/samplecode/Reachability/index.html

于 2012-09-01T14:53:51.227 回答