No Internet Connection Handling on UIWebView and NSURLRequest [duplicate]
Asked Answered
N

2

12

I have an app which is entirely web-based and needs an internet connection to navigate around. Basically a website viewed through a UIWebView.

I need to be able to tell the user that no pages can load if they have no internet connection. Is there a simple way I can do this. Perhaps a check if NSURLRequest failed?

Cheers

Niphablepsia answered 27/4, 2011 at 8:40 Comment(0)
T
5

I would look at Apple's Reachability sample code to implement this reliably. One advantage of this approach is that you can notify the user as to current network status even the user isn't actually clicking on any links in the web view.

Toadeater answered 27/4, 2011 at 8:42 Comment(0)
I
0

1>Add SystemConfiguration.framework to your project

2>import following .h files in your Connection.h file

#import <sys/socket.h>
#import <netinet/in.h>
#import <SystemConfiguration/SystemConfiguration.h>

3>declare the following class method in your Connection.h file

+(BOOL)hasConnectivity;

4>define this method in your Connection.m file

+(BOOL)hasConnectivity {

struct sockaddr_in zeroAddress;
bzero(&zeroAddress, sizeof(zeroAddress));
zeroAddress.sin_len = sizeof(zeroAddress);
zeroAddress.sin_family = AF_INET;

SCNetworkReachabilityRef reachability = SCNetworkReachabilityCreateWithAddress(kCFAllocatorDefault, (const struct sockaddr*)&zeroAddress);
if(reachability != NULL) {
    //NetworkStatus retVal = NotReachable;
    SCNetworkReachabilityFlags flags;
    if (SCNetworkReachabilityGetFlags(reachability, &flags)) {
        if ((flags & kSCNetworkReachabilityFlagsReachable) == 0)
        {
            // if target host is not reachable
            return NO;
        }

        if ((flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0)
        {
            // if target host is reachable and no connection is required
            //  then we'll assume (for now) that your on Wi-Fi
            return YES;
        }


        if ((((flags & kSCNetworkReachabilityFlagsConnectionOnDemand ) != 0) ||
             (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0))
        {
            // ... and the connection is on-demand (or on-traffic) if the
            //     calling application is using the CFSocketStream or higher APIs

            if ((flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0)
            {
                // ... and no [user] intervention is needed
                return YES;
            }
        }

        if ((flags & kSCNetworkReachabilityFlagsIsWWAN) == kSCNetworkReachabilityFlagsIsWWAN)
        {
            // ... but WWAN connections are OK if the calling application
            //     is using the CFNetwork (CFSocketStream?) APIs.
            return YES;
        }
    }
}

return NO;
}
Ilion answered 20/3, 2013 at 11:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.