我正在xcode 6上开发ios应用程序。
它基于使用NSUrlConnection
下载pdf文件的基础。
当我在ios模拟器上运行该应用程序时,NSUrlConnection
在后台完美运行,本地通知也是如此。
但是,当我在iPhone上构建并运行它时,当应用程序进入后台时,nsurlconnection会停止,并且不会显示本地通知。
有人可以指导我解决问题吗?
编辑:
我发现当应用程序进入后台时,请求可能会变得闲置。
但是,为什么这只会在iPhone上发生而在模拟器上却没有发生?
这是我的代码:
NSURL *url = [NSURL URLWithString:[BookArray[0] objectForKey:@"Link"]];
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:2.5];
NSURLConnection *PDFConnection;
PDFConnection = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES ];
最佳答案
如果您想在应用程序进入后台运行时继续下载,只需拨打beginBackgroundTaskWithExpirationHandler:
@property (nonatomic, assign) UIBackgroundTaskIdentifier backgroundTaskID;
@synthesize backgroundTaskID;
...
NSURL *url = [NSURL URLWithString:[BookArray[0] objectForKey:@"Link"]];
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:2.5];
NSURLConnection *PDFConnection;
PDFConnection = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES ];
self.backgroundTaskID = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^{
[connection cancel];
}];
然后在您的委托方法中,完成下载后应调用
endBackgroundTask:
:- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
// Error Handling
...
[[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskID];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
// Downloaded
[[UIApplication sharedApplication] endBackgroundTask:self.backgroundTaskID];
}
您可以阅读here
并确保您已获得此answer中所述的安排通知的权限
关于ios - 本地通知和(NSURLConnection后台下载)不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27080641/