2013-04-06 16 views
2

我有一個初始tableviewcontroller執行可達性檢查。這在viewDidLoad,內沒有問題,但是我想知道正確的方式重試連接,直到它通過。在我的實現文件中的相關代碼如下,我試圖插入[self ViewDidLoad]如果連接關閉,但這只是將應用程序設置爲一個循環(返回連接失敗NSLog消息),並沒有顯示UIAlertView我如何重複可達性測試,直到它工作

- (void)viewDidLoad 
{ 
    [super viewDidLoad]; 

    if(![self connected]) 
    { 
     // not connected 
     NSLog(@"The internet is down"); 
     UIAlertView *connectionError = [[UIAlertView alloc] initWithTitle:@"Connection  Error" message:@"There is no Internet Connection" delegate:self cancelButtonTitle:@"Retry" otherButtonTitles:nil, nil]; 
     [connectionError show]; 
     [self viewDidLoad]; 
    } else 
    { 
     NSLog(@"Internet connection established"); 
     UIButton *btn = [UIButton buttonWithType:UIButtonTypeInfoDark]; 
     [btn addTarget:self action:@selector(infoButtonClicked:) forControlEvents:UIControlEventTouchUpInside]; 
     self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:btn]; 
     [self start]; 
    } 
} 

回答

3

應該如何使用Reachability

  • 總是先嚐試連接。
  • 如果請求失敗,Reachability會告訴你爲什麼。
  • 如果網絡出現,Reachability會通知您。然後重試連接。

爲了接收通知,註冊通知,並開始從蘋果可達類:

@implementation AppDelegate { 
    Reachability *_reachability; 
} 

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions 
{ 
    [[NSNotificationCenter defaultCenter] 
    addObserver: self 
    selector: @selector(reachabilityChanged:) 
    name: kReachabilityChangedNotification 
    object: nil]; 

    _reachability = [Reachability reachabilityWithHostName: @"www.apple.com"]; 
    [_reachability startNotifier]; 

    // ... 
} 

@end 

要回答通知:

- (void) reachabilityChanged: (NSNotification *)notification { 
    Reachability *reach = [notification object]; 
    if([reach isKindOfClass: [Reachability class]]) { 
    } 
    NetworkStatus status = [reach currentReachabilityStatus]; 
    NSLog(@"change to %d", status); // 0=no network, 1=wifi, 2=wan 
} 

如果你喜歡使用塊代替,使用KSReachability

+0

注意:這是非ARC代碼。您可以通過在目標的「構建階段」>「編譯源代碼」部分添加編譯器標記-fno-objc-arc來標記文件不是ARC。 – Jano 2013-04-06 19:04:11

+0

嗨,感謝您的回答,風險極其沉重,第一部分代碼在哪裏(在viewDidLoad中?) – user2033055 2013-04-07 11:51:01

+0

是的,如果您希望它用於一個視圖控制器或應用程序委託(請參閱更新答案),如果你想要它的整個應用程序。不要猶豫地問,當我開始使用Objective-C時,對我來說這一切都是陌生的。 – Jano 2013-04-07 12:47:47

相關問題