我正在尝试使用后台 NSURLSession 从照片应用程序中的共享扩展上传文件。因为后台 NSURLSession 仅支持使用 uploadTaskWithRequest:WithFile: API 的上传任务,所以我首先获取从扩展中检索到的图像 URL 的 URL,将图像内容写入共享容器,然后上传新文件。似乎 NSURLSession 有权限问题,我收到此错误:
“无法为文件 file:///private/var/mobile/Containers/Shared/AppGroup/ 发出沙盒扩展...”
我知道有一些类似的帖子,但没有一个是从扩展加载 url,也没有显示将临时文件写入的位置。
这是代码:
- (void)fetchImageURLInExtensionContext:(NSExtensionContext*) context onComplete:(void (^)()) completion
{
NSExtensionItem *item = self.extensionContext.inputItems[0];
NSItemProvider *provider = item.attachments[0];
if ([provider hasItemConformingToTypeIdentifier:@"public.jpeg"]) {
[provider loadItemForTypeIdentifier:@"public.jpeg" options:nil completionHandler:^(id<NSSecureCoding> item, NSError *error) {
NSObject *obj = item;
if ([obj isKindOfClass:[NSURL class]]) {
self.imageURL = obj;
completion();
}
}];
}
}
- (void)postImage
{
// copy file to shared container
NSURL *containerURL = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"group.com.mytestgroup"];
NSString *writeToPath = [[containerURL path] stringByAppendingPathComponent:@"temp.jpg"];
BOOL success = [[NSData dataWithContentsOfURL:self.imageURL] writeToFile:writeToPath atomically:YES];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"https://api.imgur.com/3/image"]];
NSString *boundary = @"multipartboundary";
[request addValue:[NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary] forHTTPHeaderField:@"Content-Type"];
request.HTTPMethod = @"POST";
[request setValue:@"Client-ID my_imgur_client_id" forHTTPHeaderField:@"Authorization"];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"blah"];
config.sharedContainerIdentifier = @"group.com.mytestgroup";
NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
NSURLSessionTask *uploadTask = [session uploadTaskWithRequest:request fromFile:[NSURL fileURLWithPath:writeToPath]];
[uploadTask resume];
}