萬盛學電腦網

 萬盛學電腦網 >> 網絡基礎知識 >> 快速檢查網絡連接(轉載)

快速檢查網絡連接(轉載)

快速檢查網絡連接(轉載)

轉載自:?mod=viewthread&tid=31724


#import <sys/socket.h>

#import <netinet/in.h>
#import <arpa/inet.h>
#import <netdb.h>
#import <SystemConfiguration/SCNetworkReachability.h>
//Snip, you know we're in the implementation...
- (BOOL) connectedToNetwork
{
        // 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;
}
 
//call like:
-(void) start {
        if (![self connectedToNetwork]) {
                UIAlertView *alert = [[UIAlertView alloc] 
                         initWithTitle:@"Network Connection Error" 
                         message:@"You need to be connected to the internet to use this feature." 
                         delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
                [alert show];
                [alert release];
        } else {
             //do something 
        }
}

  • 上一篇iphone開發常用代碼(轉載)
  • 下一篇UINavigationController 直接pop到指定controllerView的方法(轉載)
  • copyright © 萬盛學電腦網 all rights reserved