2014-12-05 220 views
0

我有一個代碼,檢查互聯網連接是否存在。如果沒有互聯網,我會顯示警報。下面是代碼:iOS - isViewLoaded崩潰

- (void)testInternetConnection 
{ 
    __unsafe_unretained typeof(self) weakSelf = self; 
    internetReachableFoo = [Reachability reachabilityWithHostname:@"www.your-voc.com"]; 

    // Internet is reachable 
    internetReachableFoo.reachableBlock = ^(Reachability*reach) 
    { 
     // Update the UI on the main thread 
     dispatch_async(dispatch_get_main_queue(), ^{ 
      internetActivated = YES; 
      NSLog(@"Yayyy, we have the interwebs!"); 
     }); 
    }; 

    // Internet is not reachable 
    internetReachableFoo.unreachableBlock = ^(Reachability*reach) 
    { 
     // Update the UI on the main thread 
     dispatch_async(dispatch_get_main_queue(), ^{ 
      internetActivated = NO; 
      if(alertLoaded == NO){ 
       if(weakSelf.isViewLoaded && weakSelf.view.window){ 
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Pas de connexion internet" message:@"Une connexion est requise pour utiliser l'application" delegate:weakSelf cancelButtonTitle:nil otherButtonTitles:@"Réessayer", @"Mode hors-ligne", nil]; 
        [alert show]; 
        alertLoaded = YES; 
       } 
      } 
      NSLog(@"Someone broke the internet :("); 
     }); 
    }; 

    [internetReachableFoo startNotifier]; 
} 

我使用isViewLoaded和view.window就一定要僅在當前窗口是加載和顯示一個顯示警報。

但有些時候,當我關閉wifi,我的模擬器崩潰,出現以下錯誤;

-[UIScrollViewDelayedTouchesBeganGestureRecognizer isViewLoaded]: unrecognized selector sent to instance 0x7fbe73da4060 
2014-12-05 14:16:57.142 [838:117938] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UIScrollViewDelayedTouchesBeganGestureRecognizer isViewLoaded]: unrecognized selector sent to instance 0x7fbe73da4060' 

什麼是錯?

非常感謝

更新:我使用的託尼百萬版的可達性,所以testInternetConnection方法被稱爲每當網絡狀態的變化。

+0

您能否添加更多代碼?就像你如何調用這個方法一樣? – 2014-12-05 13:32:50

+0

你走了,更新了代碼。 – 2014-12-05 13:38:04

+0

你試過__strong typeof(self)weakSelf = self; – 2014-12-05 13:47:59

回答

0

您的weakSelf變量可能是一個弱指針,並且在代碼達到此點時已經釋放。

+0

看着更新的代碼,你覺得怎麼樣?感謝您的幫助 – 2014-12-05 13:35:25

+0

是的,具有'testInternetConnection'方法的對象被釋放。 Reachability類沒有問題。我們需要看看你在哪裏調用'testInternetConnection'並用object來結束。 – ugur 2014-12-05 13:47:37

+0

我在viewDidLoad和viewDidAppear中調用我的testInternetConnection! – 2014-12-05 17:46:36