iOS Share Extension issue when sharing images from Photo library

£可爱£侵袭症+ 提交于 2019-12-02 20:19:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!