Joe Tam
Joe Tam

Reputation: 622

iOS8 extension background NSURLSession sandbox error

I'm trying to upload a file from a sharing extension in the Photos app, using a background NSURLSession. Because a background NSURLSession only supports an upload task using the uploadTaskWithRequest:WithFile: API, I first get the URL for the image URL that was retrieved from the extension, write the image content to the shared container, then upload the new file. It seems like NSURLSession is having permission issues, I am getting this error:

"Failed to issue sandbox extension for file file:///private/var/mobile/Containers/Shared/AppGroup/..."

I know there are a few similar posts to this but none of them are loading an url from an extension and does not show where to write the temporary file to.

Here's the code:

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

Upvotes: 4

Views: 1690

Answers (1)

Cherpak Evgeny
Cherpak Evgeny

Reputation: 2770

workaround solution: move the file from inbox to temp directory and upload from there.

Upvotes: 0

Related Questions