UIWebView和NSURLRequest上没有Internet连接处理

时间:2011-04-27 08:40:41

标签: objective-c ipad uiwebview nsurlrequest

我有一个完全基于网络的应用程序,需要互联网连接才能导航。基本上是通过UIWebView查看的网站。

我需要能够告诉用户如果没有互联网连接,则无法加载任何页面。有一种简单的方法可以做到这一点。也许检查一下NSURLRequest是否失败了?

干杯

3 个答案:

答案 0 :(得分:6)

我会查看Apple的Reachability示例代码,以便可靠地实现这一点。这种方法的一个优点是,即使用户实际上没有点击Web视图中的任何链接,您也可以通知用户当前的网络状态。

答案 1 :(得分:2)

答案 2 :(得分:0)

1>将SystemConfiguration.framework添加到项目中

2>导入Connection.h文件中的.h文件

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

3&gt;在Connection.h文件中声明以下类方法

+(BOOL)hasConnectivity;

4&gt;在Connection.m文件中定义此方法

+(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;
}