你需要做的是使用NSURLSession而不是NSURLConnection(如果你还在使用它)
NSURLSession 和 NSURLConnection 的区别
NSURLConnection:如果我们与 NSURLConnection 有一个打开的连接并且系统中断了我们的应用程序,当我们的应用程序进入后台模式时,我们接收或发送的所有内容都会丢失。
NSURLSession:解决这个问题,也给我们进程外的下载。即使我们无权访问,它也会管理连接过程。您需要在 AppDelegate 中使用 application:handleEventsForBackgroundURLSession:completionHandler
所以使用 NSURLSession,你不需要管理或检查
您的互联网连接,因为操作系统会为您完成。
额外:如何在我的 iOS 应用中检查互联网连接
免责声明:我不确定以下框架是否可以在后台模式下运行
您可以使用框架Rechability来检查您的设备是否有互联网连接。
https://github.com/tonymillion/Reachability
它是 Apple 的 Reachability 类的直接替代品,它支持在您收到 NSNotification of reachability changed 时执行块来执行操作。
您可以在他的 repo 中查看README.md,但它使用起来非常简单。
使用 NSNotification
1
在您的 AppDelegate 中您必须调用
[Reachability reachabilityWithHostname:@"www.google.com"];
另外,您需要声明一个属性来存储该值
@property (strong, nonatomic) Reachability *reach;
所以现在您必须将以下代码放入您的application:didFinishLaunchingWithOptions:
_reach = [Reachability reachabilityWithHostname:@"www.google.com"];
2
在控制器中你需要检查是否可达状态,你必须订阅那个通知
[[NSNotificationCenter defaultCenter] addObserver:_sharedInstance selector:@selector(reachabilityDidChange:) name:@"kReachabilityChanged" object:nil];
3
现在您可以实现选择器reachabilityDidChange: 来检查现在是否已连接。放在同一个Controller中。
- (void)reachabilityDidChange:(NSNotification *)note
{
Reachability * reach = (Reachability *)[note object];
if (self.appDelegate.wasConnected != [reach isReachable]){
if ([reach isReachable]){
NSLog(@"Notification Says Reachable");
[[NSNotificationCenter defaultCenter] postNotificationName:@"ConnectionIsReachable" object:nil];
[self sendPendingOperations];
}else{
[[NSNotificationCenter defaultCenter] postNotificationName:@"ConnectionIsUnreachable" object:nil];
NSLog(@"Notification Says Unreachable");
}
self.appDelegate.wasConnected = [reach isReachable];
}
}
As you can see, we store the last connection state also in a AppDelegate property
`@property BOOL wasConnected;`
4
现在您必须订阅这些新通知(ConnectionIsReachable、ConnectionIsUnreachable)并执行您需要执行的操作。
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showNoConnectionAlert) name:@"ConnectionIsUnreachable" object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hideNoConnectionAlert) name:@"ConnectionIsReachable" object:nil];
使用块
我没有测试过这个功能,但我把官方文档复制给你
// Allocate a reachability object
Reachability* reach = [Reachability reachabilityWithHostname:@"www.google.com"];
// Set the blocks
reach.reachableBlock = ^(Reachability*reach)
{
// keep in mind this is called on a background thread
// and if you are updating the UI it needs to happen
// on the main thread, like this:
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"REACHABLE!");
});
};
reach.unreachableBlock = ^(Reachability*reach)
{
NSLog(@"UNREACHABLE!");
};
// Start the notifier, which will cause the reachability object to retain itself!
[reach startNotifier];