iOS8扩展背景NSURLSession沙箱错误

时间:2014-09-09 23:01:35

标签: ios ios8 nsurlsession nsurlsessionconfiguration nsurlsessiontask

我正在尝试使用后台NSURLSession从照片应用中的共享扩展程序上传文件。因为后台NSURLSession仅支持使用uploadTaskWithRequest:WithFile:API的上传任务,所以我首先获取从扩展中检索到的图像URL的URL,将图像内容写入共享容器,然后上载新文件。似乎NSURLSession有权限问题,我收到此错误:

“无法为文件文件发布沙箱扩展名:/// private / var / mobile / Containers / Shared / AppGroup / ...”

我知道有一些类似的帖子,但没有一个从扩展中加载网址,也没有显示临时文件的写入位置。

以下是代码:

- (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];
}

1 个答案:

答案 0 :(得分:0)

变通方法解决方案:将文件从收件箱移至临时目录并从那里上传。