2013-06-12 231 views
0

大家。互聯網連接測試

您認爲以下代碼適用於檢查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 
    } 
+0

至於何時重試或等待可達通知: http://stackoverflow.com/a/15854823/412916 – Jano

回答

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 

} 
+0

謝謝你的互聯網連接測試的新選擇。 – George

+0

@喬治歡迎您..... – Venkat