代码之家  ›  专栏  ›  技术社区  ›  soleil

iOS-何时加载外部数据

  •  0
  • soleil  · 技术社区  · 12 年前

    在我的应用程序委派中,我有以下内容:

    Reachability* reach = [Reachability reachabilityWithHostname:@"www.google.com"];
    
    [[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(reachabilityChanged:) 
                                                 name:kReachabilityChangedNotification 
                                               object:nil];
    
    [reach startNotifier];
    
    HomeViewController_iPhone *homeViewController = [[HomeViewController_iPhone alloc] initWithNibName:@"HomeViewController_iPhone" bundle:nil];
    homeViewController.managedObjectContext = self.managedObjectContext;
    UINavigationController *homeNavController = [[UINavigationController alloc] initWithRootViewController: homeViewController];
    homeNavController.navigationBar.barStyle = UIBarStyleBlackTranslucent;
    
    self.tabBarController.viewControllers = [NSArray arrayWithObjects:homeNavController, nil];
    
    ...
    
    -(void)reachabilityChanged:(NSNotification*)note
    {
    Reachability * reach = [note object];
    
    if([reach isReachable])
    {
        NSLog(@"Notification Says Reachable");
        self.isConnected = YES;
    }
    else
    {
        NSLog(@"Notification Says UN-Reachable");
        self.isConnected = NO;
    }
    }
    

    问题是,在我的HomeViewController(viewDidLoad)中,我这样做:

    AppDelegate *appDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    
    if (appDelegate.isConnected)
    {
        dispatch_async(kBgQueue, ^{
            NSData* data = [NSData dataWithContentsOfURL: kFeedURL];
            [self performSelectorOnMainThread:@selector(fetchedData:) 
                                   withObject:data waitUntilDone:YES];
        });
    }
    

    但appDelegate.isConnected始终为NO,即使我有连接。我认为检查是在Reachability类建立连接之前进行的。但是我在哪里打电话来获取数据呢?我已经尝试过viewDidLoad和viewWillAppear,但isConnected在这两个点上仍然是NO。

    1 回复  |  直到 12 年前
        1
  •  0
  •   soleil    12 年前

    如dnstevenson建议的答案所示,在创建视图控制器之前,通过在应用程序代理中执行此操作来解决问题。

    Reachability *reachability = [Reachability reachabilityForInternetConnection];    
    NetworkStatus internetStatus = [reachability currentReachabilityStatus];
    if (internetStatus != NotReachable) {
        //my web-dependent code
    }
    else {
        //there-is-no-connection warning
    }