iOS判斷是否存在網路

來源:互聯網
上載者:User

標籤: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, (structsockaddr *)&zeroAddress);

    SCNetworkReachabilityFlags flags;

    BOOL didRetrieveFlags =SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);

    CFRelease(defaultRouteReachability);

    if (!didRetrieveFlags)

    {

         returnNO;

    }


    BOOL isReachable = flags &kSCNetworkFlagsReachable;

    BOOL needsConnection = flags &kSCNetworkFlagsConnectionRequired;

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

}



看到這個方法非常不錯,以達提高自己,方便他人,是為記。


iOS判斷是否存在網路

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.