我正在构建一个应用程序,它需要同步离线数据与服务器,无论何时互联网连接是活跃的。因此,目前,如果在将数据推送到服务器之间丢失internet连接,则会将其保存在数据库中,并且每当连接处于活动状态时,它就会将数据推送到服务器。我正在使用新的可达类版本: 3.5来自苹果。根据他们对特定视图控制器的示例,我可以这样做
- (void)viewDidLoad
{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reachabilityChanged:) name:kReachabilityChangedNotification object:nil];
self.internetReachability = [Reachability reachabilityForInternetConnection];
[self.internetReachability startNotifier];
[self updateInterfaceWithReachability:self.internetReachability];
}
/*!
* Called by Reachability whenever status changes.
*/
- (void) reachabilityChanged:(NSNotification *)note
{
Reachability* curReach = [note object];
NSParameterAssert([curReach isKindOfClass:[Reachability class]]);
[self updateInterfaceWithReachability:curReach];
}
- (void)updateInterfaceWithReachability:(Reachability *)reachability
{
if (reachability == self.internetReachability)
{
//Internet is active again- call api to push data to server
}
}这将适用于特定的视图控制器。在新的Reachability类中,还有其他方法可以检查整个应用程序的运行情况吗?或者,我是否必须在每个视图控制器中进行此检查,以检查是否有活动的internet连接?
发布于 2014-10-08 09:31:13
您可以通过应用程序委托检查它。我以前做过这样的事。
@property (strong,nonatomic)Reachability *reach;
@property(nonatomic)NetworkStatus netStatus;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(checkNetworkStatus:)
name:kReachabilityChangedNotification object:nil];
reach = [Reachability reachabilityForInternetConnection];
[reach startNotifier];
[self checkNetworkStatus:nil];
}
- (void)checkNetworkStatus:(NSNotification *)notice
{
netStatus = [reach currentReachabilityStatus];
if (netStatus == NotReachable)
{
NSLog(@"The internet is down.");
// do stuff when network gone.
}
else
{
NSLog(@"The internet is working!");
// do stuff when internet comes active
[[NSNotificationCenter defaultCenter] postNotificationName:@"INTERNET_AVAILABLE" object:nil];
}
}现在,当互联网出现时,它会发出通知。在检查internet连接所需的所有视图中添加通知的观察者。它的工作是检查整个应用程序的互联网。并合成了属性。
========编辑
在应用程序中.h
+ (BOOL)isActiveInternet;在应用程序委派中。
+ (BOOL)isActiveInternet
{
netStatus = [reach currentReachabilityStatus];
if (netStatus == NotReachable)
{
NSLog(@"The internet is down.");
// do stuff when network gone.
return FALSE;
}
else
{
NSLog(@"The internet is working!");
// do stuff when internet comes active
[[NSNotificationCenter defaultCenter] postNotificationName:@"INTERNET_AVAILABLE" object:nil];
return TRUE;
}
}以便您可以在项目中的任何地方直接调用此方法,如
if([appdelegate isActiveInternet]) {
//yes net available do your stuff
}发布于 2014-10-08 07:21:05
将数据推送到服务器时,使用的是app委托,而不是特定的视图控制器。这样,您的reachibily就会出现在and中,并且您可以简单地从视图控制器中调用Appdelegate的方法来保存数据或推送到服务器。
如果您不想使用Appdelegate,请为此使用单例类。
发布于 2014-10-08 07:25:18
我和其他人一起工作的项目使用了一个ReachabilityManager,它使用了单例模式,如可达性所描述的那样。
您可以创建一个UIViewController的子类,该子类添加对视图加载中的通知的观察,并且所有视图控制器都将此视图控制器子类。
https://stackoverflow.com/questions/26250944
复制相似问题