2013-02-19 69 views
0

假設我其實有一個互聯網連接,我用這個代碼知道,如果設備通過WiFi或不連接:是否有效檢查iOS中的互聯網可達性?

+ (BOOL)hasWiFiConnection { 

    Reachability *reachability = [Reachability reachabilityForInternetConnection]; 
    [reachability startNotifier]; 

    NetworkStatus status = [reachability currentReachabilityStatus]; 

    if (status == ReachableViaWiFi) { 

     return YES; 

    } else { 

     return NO; 
    } 
} 

是該代碼運行速度快?

我在爲圖片生成URL時使用它(以便我知道我是否加載高分辨率圖片或低分辨率圖片)。這些圖片以列表視圖顯示(每行3個)。當我滾動列表時,函數每秒被調用幾次。這是否有效?

回答

2

如果你不想使用可達性類使用下面的代碼。

 @interface CMLNetworkManager : NSObject 
     +(CMLNetworkManager *) sharedInstance; 

     -(BOOL) hasConnectivity; 
      @end 

實施

  @implementation CMLNetworkManager 

     +(CMLNetworkManager *) sharedInstance { 
    static CMLNetworkManager *_instance = nil; 
@synchronized(self) { 
    if(_instance == nil) { 
     _instance = [[super alloc] init]; 
    } 
} 
return _instance; 
} 

    -(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) { 
    //NetworkStatus retVal = NotReachable; 
    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 

使用帶班的布爾方法共享實例進行任何你想要

+0

感謝您的選擇,但你有什麼解決方案和我的優點/缺點?你能多解釋一下嗎? – Alexis 2013-02-19 14:27:04

+0

關於此詳細文檔https://developer.apple.com/library/mac/#documentation/SystemConfiguration/Reference/SCNetworkReachabilityRef/Reference/reference.html – Madhu 2013-02-19 14:31:18

+0

在CMLNetworkManager.mfile中添加此項#import #import #import Madhu 2013-02-19 14:32:32