问题
Below is a code that I use to share images within my "ShareViewController.m".
NSExtensionItem *item = [self.extensionContext.inputItems objectAtIndex:i];
NSItemProvider *itemProvider = item.attachments.firstObject;
if ([itemProvider hasItemConformingToTypeIdentifier:(NSString *)kUTTypeURL]) {
[itemProvider loadItemForTypeIdentifier:(NSString *)kUTTypeURL options:nil completionHandler:^(NSData *data, NSError *error) {
NSLog(@"%@", data);
// the rest of uploading script goes here
}];
}
It all works fine if I share an image from WhatsApp. But it doesn't work if I want to share an image from Photo Library or from Facebook Messenger.
Does anyone know what the problem might be?
Thanks
回答1:
Here is how I solved it. I got rid of (NSString *)kUTTypeURL]
and added itemProvider.registeredTypeIdentifiers
to get array with all the available type identifiers. Then I'm just using the first one available as registeredTypeIdentifiers.firstObject
.
Also, very important, NSData *data
got changed to id<NSSecureCoding> item
which makes it a bit different to get the NSData
from it. That's important especially when sharing images from Messenger - they have type identifier "public.image"
rather than "public.jpeg"
or "public.url"
like in Photos library or WhatsApp.
NSExtensionItem *item = [self.extensionContext.inputItems objectAtIndex:i];
NSItemProvider *itemProvider = item.attachments.firstObject;
// get type of file extention (jpeg, file, url, png ...)
NSArray *registeredTypeIdentifiers = itemProvider.registeredTypeIdentifiers;
if ([itemProvider hasItemConformingToTypeIdentifier:registeredTypeIdentifiers.firstObject) {
[itemProvider loadItemForTypeIdentifier:registeredTypeIdentifiers.firstObject options:nil completionHandler:^(id<NSSecureCoding> item, NSError *error) {
NSData *imgData;
if([(NSObject*)item isKindOfClass:[NSURL class]]) {
imgData = [NSData dataWithContentsOfURL:(NSURL*)item];
}
if([(NSObject*)item isKindOfClass:[UIImage class]]) {
imgData = UIImagePNGRepresentation((UIImage*)item);
}
// the rest of uploading script goes here
}];
}
来源:https://stackoverflow.com/questions/47385012/ios-share-extension-issue-when-sharing-images-from-photo-library