我的目标是在应用程序处于后台时将数据/图像发送到服务器。在iOS7中,我们可以使用后台fetch来完成此操作。但是后台抓取只提供30秒的时间限制。我发送到服务器的数据可能需要更长的时间,因为它有更多的图像。在谷歌搜索时,我遇到了后台传输服务,它提供了无限制的时间来在后台上传/下载数据。后台取码是否可以发起后台转账服务?如果是这样,如何处理它。
发布于 2015-12-14 22:47:52
无论何时你想要开始你的上传/下载(在你的例子中是在你30秒的后台抓取期间),执行下面的代码行:
NSString *downloadURLString = //Your link here;
NSURL* downloadURL = [NSURL URLWithString:downloadURLString];
NSURLRequest *request = [NSURLRequest requestWithURL:downloadURL];
// Create a background session
static NSURLSession *session = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSString *identifier = @"com.yourcompany.yourapp";
NSURLSessionConfiguration* sessionConfig = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:identifier];
session = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];
});
//Init a NSURLSessionDownloadTask with the just-created request and resume it
NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:request];
[task resume];
});另外,别忘了实现这些委托方法:
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didFinishDownloadingToURL:(NSURL *)location;
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didWriteData:(int64_t)bytesWritten
totalBytesWritten:(int64_t)totalBytesWritten
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite;
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask
didResumeAtOffset:(int64_t)fileOffset
expectedTotalBytes:(int64_t)expectedTotalBytes;有关详细示例,请查看this示例应用程序
https://stackoverflow.com/questions/32003627
复制相似问题