IOS8 NSURLSession Source Code
I am trying to load a file from a sharing extension in Photos app using a background NSURLSession. Since the background NSURLSession only supports the upload task using the uploadTaskWithRequest: WithFile: API method, I first get the image url url that was obtained from the extension, write the image content to the shared container, and then upload a new file. NSURLSession seems to be having permission issues, I get this error:
"Failed to release sandbox extension for file file: /// private / var / mobile / Containers / Shared / AppGroup / ..."
I know there are several similar posts, but none of them load the url from the extension and show where to write the temp file.
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];
}
+3
source to share