我已经在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)
{...
我已经在多个 View 上实现了它(这似乎是导致问题的原因。
对于多 View 应用程序,建议的方法是什么?
最佳答案
[RKClient sharedClient]单例已经具有该属性(reachabilityObserver)。随意使用那个。
if ([[[RKClient sharedClient] reachabilityObserver] isReachabilityDetermined] && [[RKClient sharedClient] isNetworkReachable]) {
....
}
您还可以订阅RKReachabilityObserver通知(如果要在可达性状态更改时采取任何措施)
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(reachabilityStatusChanged:)
name:RKReachabilityDidChangeNotification object:nil];
关于xcode - 在RestKit中实现RKReachabilityObserver的最佳方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/8762710/