首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >调用Reachability后,网络状态更改为0

调用Reachability后,网络状态更改为0
EN

Stack Overflow用户
提问于 2013-02-13 09:39:53
回答 1查看 2.5K关注 0票数 1

在我的iOS应用程序中,我需要使用Reachability来完成以下任务:

  1. 当呈现视图控制器时,应用程序需要检查连接状态,并相应地(在线或脱机)显示连接图标图像。
  2. 当用户停留在视图控制器上时,如果internet连接状态发生变化,应用程序将被通知更改,然后相应地执行一些任务。

我在我的应用程序中使用了托尼百万生成的Reachability类,但是发生了一件奇怪的事情:调用了startNotified方法后,可达状态变为0(NotReachable)

以下是我的代码:

BTLandingViewController.h

代码语言:javascript
复制
#import <UIKit/UIKit.h>
#import "MBProgressHUD.h"
#import "Reachability.h"

@interface BTLandingViewController : UIViewController <UIAlertViewDelegate>
{
    __weak IBOutlet UIImageView *internetIndicator;

    MBProgressHUD *hud;
    Reachability *reach;

    UIAlertView *emptyRecordsAlert;
    UIAlertView *syncReminderAlert;
}

@end

是BTLandingViewController.m代码的一部分

代码语言:javascript
复制
#import "BTLandingViewController.h"

@interface BTLandingViewController ()
@end
@implementation BTLandingViewController
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Initialize reachability
        reach = [Reachability reachabilityWithHostname:BTReachTestURL];
    }
    return self;
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    // Register with reachability changed notification
    [[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(reachabilityChanged:)
                                             name:kReachabilityChangedNotification
                                           object:nil];

    NetworkStatus internetStatus = [reach currentReachabilityStatus]; // value = 1 or 2

    ***// PS: If there is connection, before [reach startNotifier], the internetStatus's   value reflects the connection status (1 or 2)***

    // Start notify reachability change
    [reach startNotifier];

    internetStatus = [reach currentReachabilityStatus]; // Value = 0;

    ***// PS: Even if there is connection, after [reach startNotifier], the internetStatus's value becomes 0***
}

谢谢你的帮助。

EN

回答 1

Stack Overflow用户

发布于 2013-02-14 02:33:19

通过绕过我前面提到的startNotifier陷阱,我终于解决了这个问题。调用startNotifier确实会将网络状态更改为0,但是在呈现视图控制器时,我声明了一个变量来存储初始网络状态。然后在方法中使用if语句中变量的值,该方法处理reachabilityChanged通知触发的操作。以下是我的代码:

BTLandingViewController.h

代码语言:javascript
复制
#import <UIKit/UIKit.h>
#import "MBProgressHUD.h"
#import "Reachability.h"

@interface BTLandingViewController : UIViewController <UIAlertViewDelegate>
{
    __weak IBOutlet UIImageView *internetIndicator;

    MBProgressHUD *hud;
    NSInteger initialNetworkStatus;

    UIAlertView *emptyRecordsAlert;
    UIAlertView *syncReminderAlert;  
}

@end

BTLandingViewController.m

代码语言:javascript
复制
#import "BTLandingViewController.h"
#import "BTSyncEngine.h"
#import "BTInstructorLoginViewController.h"
#import "BTGlobalParams.h"

@interface BTLandingViewController ()

@end

@implementation BTLandingViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {

    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewDidUnload {
    internetIndicator = nil;
    [super viewDidUnload];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    // Register with sync complete notification
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(syncCompleted:) name:@"BTSyncEngineSyncCompleted" object:nil];

    // Register with reachability changed notification
    [[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(reachabilityChanged:)
                                             name:kReachabilityChangedNotification
                                           object:nil];

    Reachability *reach = [Reachability reachabilityWithHostname:BTReachTestURL];

    reach.reachableBlock = ^(Reachability * reachability){
        dispatch_async(dispatch_get_main_queue(), ^{
            initialNetworkStatus = 1;

            [internetIndicator setImage:[UIImage imageNamed:@"online_indicator.png"]];

            // Start syncing local records with the remote server
            [[BTSyncEngine sharedEngine] startSync];
            hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.labelText = @"Sync in progress";
        });
    };

    reach.unreachableBlock = ^(Reachability * reachability)
    {
        dispatch_async(dispatch_get_main_queue(), ^{
            initialNetworkStatus = 0;

            [internetIndicator setImage:[UIImage imageNamed:@"offline_indicator.png"]];

            // If the initial sync has been executed
            // then use the cached records on the device
            if ([[BTSyncEngine sharedEngine] initialSyncComplete]) {
                // Go to instructor login screen
                BTInstructorLoginViewController *instructorLoginViewController = [[BTInstructorLoginViewController alloc] init];
                [instructorLoginViewController setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
                [self presentViewController:instructorLoginViewController animated:YES completion:nil];
            }
            // If the initial sync has not been executed
            // show an alert view
            else {
                emptyRecordsAlert = [[UIAlertView alloc] initWithTitle:@"Alert" message:@"Please connect to the internet to load data for the first time use." delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
                [emptyRecordsAlert show];
            }

        });
    };

    [reach startNotifier];

}

- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];

    // Unregister with reachability changed notification
    [[NSNotificationCenter defaultCenter] removeObserver:self name:kReachabilityChangedNotification object:nil];

    // Unregister with sync complete notification
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"BTSyncEngineSyncCompleted" object:nil];
}

- (void)syncCompleted:(NSNotification *)note
{
    // Update the global sync completed flag
    [[BTGlobalParams sharedParams] setSyncCompleted:YES];

    // Hide syncing indicator
    [MBProgressHUD hideHUDForView:self.view animated:YES];

    // Go to instructor login screen
    BTInstructorLoginViewController *instructorLoginViewController = [[BTInstructorLoginViewController alloc] init];
    [instructorLoginViewController setModalTransitionStyle:UIModalTransitionStyleCrossDissolve];
    [self presentViewController:instructorLoginViewController animated:YES completion:nil];
}

- (void)reachabilityChanged:(NSNotification *)note
{
    Reachability *reach = [note object];

    if ([reach isReachable] && !initialNetworkStatus) {

        [internetIndicator setImage:[UIImage imageNamed:@"online_indicator.png"]];

        // Start syncing local records with the remote server
        [[BTSyncEngine sharedEngine] startSync];
        hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        hud.labelText = @"Sync in progress";

    }
}

@end
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14850440

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档