我想在共享扩展中上传从服务器下载的数据,但是上传任务被延迟,它将在下次我在共享扩展中按下发布按钮时继续。我在Document中发现这条消息描述了“discretionary”,是不是表示上传任务是在APP处于后台状态时启动的,所以系统可能会延迟上传。
对于在您的应用程序处于后台时启动的传输,系统始终自行决定启动传输 - 换句话说,系统假定此属性为 YES 并忽略您指定的任何值。
以下是代码:
- (void)didSelectPost {
NSURLSession *session = [self configureSession];
NSString *downLoadStr = [NSString stringWithFormat:@"https://apis.live.net/v5.0/%@/content?access_token=%@", [shareProfile objectForKey:@“PATH”], accesToken];
mDownloadTask = [session downloadTaskWithURL:downUrl];
[mDownloadTask resume];
[self.extensionContext completeRequestReturningItems:[self.extensionContext inputItems] completionHandler:nil];
}
- (NSURLSession *) configureSession {
static NSURLSession *session = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
NSURLSessionConfiguration* config = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"com.test.background_shareext"];
// To access the shared container you set up, use the sharedContainerIdentifier property on your configuration object.
config.sharedContainerIdentifier = @"group.test.background”;
session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
});
return session;
}
- (void) URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location{
if (location != nil) {
NSString *str = [NSString stringWithContentsOfFile:[location path] encoding:NSUTF8StringEncoding error:nil];
char *utfString = [[@"" stringByAppendingFormat:@"%@\n%@\n", str, @"test"] UTF8String];
NSData *uploadData = [NSData dataWithBytes:utfString length:strlen(utfString)];
NSString *uploadUrlStr = [NSString stringWithFormat:@"https://apis.live.net/v5.0/%@/files/%@?suppress_response_codes=true&overwrite=true&access_token=%@", path, file, accesToken];
NSURL *uploadUrl = [NSURL URLWithString:uploadUrlStr];
NSMutableURLRequest *uploadReq = [NSMutableURLRequest requestWithURL:uploadUrl cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:HTTP_REQUEST_TIMEOUT_INTERVAL];
[uploadReq setHTTPMethod:@"PUT"];
[uploadReq setHTTPBody:uploadData];
NSURLSession *session = [self configureSession];
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithStreamedRequest:uploadReq];
[uploadTask resume];
}else{
NSLog(@"download task location is nil");
}
}
更新:
在我分享了几次之后,下载任务可能会停止,并一直运行到我稍后分享。