I currently have a share extension set up that will upload an image selected from the Photo app to a server. This works fine using the code below.
int fileNum=10;
NSItemProvider *attachment = inputItem.attachments[0];
if ([attachment hasItemConformingToTypeIdentifier:(NSString*)kUTTypeImage])
{
[attachment loadItemForTypeIdentifier:(NSString*)kUTTypeImage options:nil completionHandler:^(id item,NSError *error)
{
if (item)
{
NSLog (@"image %@",item);
//upload image here
NSData *data=[NSData dataWithContentsOfURL:item];
activityRecord.activityType=@"Images";
AppRecord *appRecord=[[AppRecord alloc] init];
appRecord.fileName=[NSString stringWithFormat:@"activity_%@%i(%i).jpg",activityRecord.supplierID,activityRecord.activityID,fileNum];
appRecord.fileBytes=data;
[fileRecords addObject:appRecord];
activityRecord.activityFiles=fileRecords;
[[Settings getInstance] uploadActivityRecord:activityRecord withDelegate:self];
[self.extensionContext completeRequestReturningItems:@[] completionHandler:nil];
}
}];
}
I had a previous problem where the loadItemForTypeIdentifier
method wasn't being called, and it was resolved by calling completeRequestReturningItems
within the completion block. The problem I have now is that if I want to upload multiple files then I need to call loadItemForTypeIdentifier
within a for loop (for each image) but how can I do that if the completeRequestReturningItems
method will be called after the first image/item?
Many Thanks Paul
I ran into the same problem recently and was able to resolve it by adding a counter and counting down as the images successfully completed their block. Within the loadItemForTypeIdentifier
completion block I then check to see if all items have been called before calling the completeRequestReturningItems
within a dispatch_once
block (just for safety's sake).
__block NSInteger imageCount;
static dispatch_once_t oncePredicate;
NSItemProvider *attachment = inputItem.attachments[0];
if ([attachment hasItemConformingToTypeIdentifier:(NSString*)kUTTypeImage])
{
[attachment loadItemForTypeIdentifier:(NSString*)kUTTypeImage options:nil completionHandler:^(NSData *item ,NSError *error)
{
if (item)
{
// do whatever you need to
imageCount --;
if(imageCount == 0){
dispatch_once(&oncePredicate, ^{
[self.extensionContext completeRequestReturningItems:@[] completionHandler:nil];
});
}
}
}];
}
I can't say I feel like this is an overly elegant solution however, so if someone knows of a more appropriate way of handling this common use case I'd love to hear about it.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments