加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

xcode – 在RestKit中实现RKReachabilityObserver的最佳方法

发布时间:2020-12-15 01:51:21 所属栏目:百科 来源:网络整理
导读:我在Xcode / RestKit中编写了一个基于选项卡的应用程序,并尝试使用RKReachabilityObserver来确定设备上的Internet连接. 理想情况下,我希望在我的应用程序中有一个单一的可达性变量(如果这是可能的),但目前我的实现是按照下面的代码,并且在我的4个选项卡上复
我在Xcode / RestKit中编写了一个基于选项卡的应用程序,并尝试使用RKReachabilityObserver来确定设备上的Internet连接.

理想情况下,我希望在我的应用程序中有一个单一的可达性变量(如果这是可能的),但目前我的实现是按照下面的代码,并且在我的4个选项卡上复制时效果不佳.

如果有人对更好的方法有任何建议,我真的很感激你的意见.

View.h

@property (nonatomic,retain) RKReachabilityObserver *observer;

View.m

@interface AppViewController()
{
    RKReachabilityObserver *_observer;
}
@property (nonatomic) BOOL networkIsAvailable;
@synthesize observer = _observer;

-(id)initWithCoder:(NSCoder *)aDecoder {

    if ((self = [super initWithCoder:aDecoder])) {

        self.observer = [[RKReachabilityObserver alloc] initWithHost:@"mydomain"];
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(reachabilityChanged:)
                                                     name:RKReachabilityDidChangeNotification
                                                   object:_observer];
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // determine network availability
    if (! [_observer isReachabilityDetermined]) {
        _networkIsAvailable = YES;
    }
    else
    {
        _networkIsAvailable = NO;
    }

    _text.returnKeyType = UIReturnKeyDone;
    _text.delegate = self;
}

- (void)reachabilityChanged:(NSNotification *)notification {
    RKReachabilityObserver* observer = (RKReachabilityObserver *) [notification object];
    if ([observer isNetworkReachable]) {
        if ([observer isConnectionRequired]) {
            _networkIsAvailable = YES;
            NSLog(@"Reachable");
            return;
        }
    } 
    else 
    {
        _networkIsAvailable = NO;
        NSLog(@"Not reachable");
    }
}

然后在我看来,我只是做….

if (_networkIsAvailable == YES)
    {...

我已经在多个视图上实现了这个(这似乎导致了问题.

多视图应用程序的建议方法是什么?

解决方法

[RKClient sharedClient]单例已经具有该属性(reachabilityObserver).随意使用那个.

if ([[[RKClient sharedClient] reachabilityObserver] isReachabilityDetermined] && [[RKClient sharedClient] isNetworkReachable]) {
    ....
}

您还可以订阅RKReachabilityObserver通知(如果您希望在可达性状态更改时执行任何操作)

[[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(reachabilityStatusChanged:) 
                                                 name:RKReachabilityDidChangeNotification object:nil];

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读