2013-03-12 53 views
0

我想在連接可用時觸發動作。有可用的手動檢查互聯網連接的解決方案。我發現的一種方法是使用NSTimer在固定的時間間隔內檢查互聯網連接。但它是檢查它的最有效方法嗎?如果不是,這有什麼正確的解決方案?連接可用後立即觸發動作

+0

爲什麼不直接使用'Reachability'狀態並在狀態更改時執行操作? – nsgulliver 2013-03-12 16:55:53

+0

問題是如何不斷檢查可達性狀態。 – 2013-03-12 17:00:19

+2

如果您已經正確添加了觀察者,那麼只要網絡狀態發生變化,它就會更改狀態並提示您。 – nsgulliver 2013-03-12 17:02:12

回答

0

檢查reachability code由apple.In提供appdelegate.m你可以看到這個method.It會通知其上的網絡change.Work

//Called by Reachability whenever status changes. 
- (void) reachabilityChanged: (NSNotification*)note 
{ 
    Reachability* curReach = [note object]; 
    NSParameterAssert([curReach isKindOfClass: [Reachability class]]); 
    [self updateInterfaceWithReachability: curReach]; 
} 
+0

太棒了!謝謝!將在2分鐘內接受答案。 – 2013-03-12 17:06:57

2

在這裏,你怎麼能觀察者註冊和聽吧,你的應用程序正在收聽kReachabilityChangedNotification &每當網絡狀態發生變化時都會提示您。

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityHasChanged:) name:kReachabilityChangedNotification object:nil]; 

    internetReachable = [[Reachability reachabilityForInternetConnection] retain]; 
    [internetReachable startNotifier]; 



-(void) reachabilityHasChanged:(NSNotification *)notice 
{ 
    // called after network status changes 
    NetworkStatus internetStatus = [internetReachable currentReachabilityStatus]; 
    switch (internetStatus) 
    { 
     case NotReachable: 
     { 
      NSLog(@"The internet is down."); 


      break; 
     } 
     case ReachableViaWiFi: 
     { 
      NSLog(@"The internet is working via WIFI."); 


      break; 
     } 
     case ReachableViaWWAN: 
     { 
      NSLog(@"The internet is working via WWAN."); 


      break; 
     } 
    } 
} 
+0

這看起來像是像我這樣的NSNovice更簡單的解決方案。:) – 2013-03-12 17:11:32

+0

這是'Reachability'如何工作! – nsgulliver 2013-03-12 17:12:59

+0

我在你的解決方案中的前三行添加到了我的AppDelegate.m didFinishLaunchingWith ..並在ReachabilityHasChanged-Not Reachable中添加了一個alerview。但不知何故它不會調用這個方法 – 2013-03-12 18:48:16