互联网连接测试

时间:2013-06-12 01:18:53

标签: iphone ios

大家。

您认为以下代码适合检查iOS中的互联网连接吗?如果我保留它,我可以遇到任何问题吗?太弱了吗? 到现在为止,它对我没有任何问题。你怎么看? 谢谢。

    stringToURL = [NSString [NSString stringWithFormat: @"http://www.mycompany.com/File.csv"];
    url = [NSURL URLWithString:stringToURL];
    NSError *error = nil;
    content = [NSString stringWithContentsOfURL:url encoding:NSUTF8StringEncoding error:&error];
    if (error != nil) {
            //Do something
    } else {
            //Keep running the app
    }

2 个答案:

答案 0 :(得分:1)

使用以下代码检查互联网连接,

.h

#import <Foundation/Foundation.h>

@interface NetworkConnectivity : NSObject

+ (BOOL)hasConnectivity;

@end

.m

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

@implementation NetworkConnectivity


+ (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) {

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


@end

然后检查你想要的地方,

if ([NetworkConnectivity hasConnectivity]) {

    // Internet available

} else {

    // Internet not available

}

答案 1 :(得分:0)

将Tony Million的Reachability.h版本和Reachability.m添加到项目中 在此处找到:https://github.com/tonymillion/Reachability