Check for Internet in UIWebView App on jQuery .click()
-
29-06-2021 - |
Question
I use this code to check for internet when the app opens for the first time:
//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);
}
I have a UIWebView app that has a jQuery .click() function. Is there a way to check for Internet again once the user clicks that button?
Solution
Take a look at Apple's sample code. The Reachability project shows how to detect a connection
http://developer.apple.com/iphone/library/samplecode/Reachability/index.html
OTHER TIPS
Keep in mind, a click doesn't necessarily request more resources over a network connection.
UIWebViewDelegate
has a webView:shouldStartLoadWithRequest:navigationType
selector that will be your friend here. To trigger it whenever you want (on click or other actions), set the source of a hidden iframe to some dummy value, and check for that value in your delegate method (which will run your test and return NO
.
I recommend not exiting when there is no connection though, since users may see it as a crash, especially if their connection loss is only temporary (going through a tunnel). Also, repeatedly testing for connection may slow down your app unnecessarily, and incur more data charges for the user.
you could do like that:
in function click() you should add this code:
window.location = "fake://myApp/checkForInternet";
in your Objective-C code add this one:
-(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;
}
note that in this example -webView:shouldStartLoad... is called only once per event in webView. I can provide more complexed code if you want to do checking twice or more in one javascript function at one event
read about checking for reachability you can, as @Rajneesh071 said, in Apple documentation or here is the project on GitHub
If you're using Apple's Reachability code or similar then you want the currentReachabilityStatus
method; otherwise call the underlying SCNetworkReachabilityGetFlags function