码迷,mamicode.com
首页 > 移动开发 > 详细

iOS判断是否存在网络

时间:2014-10-09 15:54:48      阅读:205      评论:0      收藏:0      [点我收藏+]

标签:ios

Every iPhone developer that has integrated a network connection based application has had to follow the Apple HID (Human Interface Design) rules. This means, that in order to get the Apple reviewers to sign-off on your application, you have to pass the network connectivity test. Basically, in the case of a catastrophic network disconnect issue with 3G and WiFi does your application properly alert the user that it will not perform properly without the usage of the network? I’ve seen a lot of workaround techniques where users attempt to do an HTTP GET on say Google or some other website. Clearly, this kind of technique will work sporadically in an unknown environment common to the mobile device. I mean, imagine causing your application users to sit through a 5-30 second web request timeout. The end-user will probably believe that the application is hung. The ideal solution happens to be handed to us in the API Framework SCNetworkReachability. (Make sure your codebase is linked properly with the “SystemConfiguration” Framework).

It’s worked for me and I recommend it for doing a simple network connectivity test.

  1. #import <sys/socket.h>
  2. #import <netinet/in.h>
  3. #import <arpa/inet.h>
  4. #import <netdb.h>
  5. #import <SystemConfiguration/SCNetworkReachability.h>
  6. //Snip, you know we‘re in the implementation...

#pragma mark -是否存在网络

- (BOOL)isNetworkReachable{

    // Create zero addy

    struct sockaddr_in zeroAddress;

    bzero(&zeroAddress, sizeof(zeroAddress));

    zeroAddress.sin_len = sizeof(zeroAddress);

    zeroAddress.sin_family = AF_INET;

    // Recover reachability flags

    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);

    SCNetworkReachabilityFlags flags;

    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);

    CFRelease(defaultRouteReachability);

    if (!didRetrieveFlags)

    {

         return NO;

    }


    BOOL isReachable = flags & kSCNetworkFlagsReachable;

    BOOL needsConnection = flags & kSCNetworkFlagsConnectionRequired;

    return (isReachable && !needsConnection) ? YES : NO;

}



看到这个方法非常不错,以达提高自己,方便他人,是为记。


iOS判断是否存在网络

标签:ios

原文地址:http://blog.csdn.net/leochang130731/article/details/39925961

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!