iOS Share Extension从其他APP获取文件

参考链接:
https://stackoverflow.com/questions/33163431/how-to-get-image-form-url-passed-by-share-extension-to-an-app

存:
NSURL * urlTemp = 从self.extensionContext.inputItems属性中的NSExtensionItem对象的attachments属性中的NSItemProvider的loadItemForTypeIdentifier方法里获取的,例如,从微信中分享的就是源文件在微信中的路径。
NSData *urlData = [NSData dataWithContentsOfURL:urlTemp];//获取源路径下的数据
NSURL *sharedContainer = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:@"group.com.AppShareDemo"];
NSString *dirPath = [sharedContainer.path stringByAppendingPathComponent:[NSString stringWithFormat:@"/%@",[urlTemp lastPathComponent]]];//创建/Shared/AppGroup/路径下的目的路径
BOOL b = [urlData writeToFile:dirPath atomically:YES];//把数据写进目的路径

                 NSUserDefaults *userDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.com.AppShareDemo"];
                 [userDefaults setValue:dirPath forKey:@"shareFilePath"];//把目的路径传给宿主APP(container applciation)

取:
NSUserDefaults *userDefaults = [[NSUserDefaults alloc] initWithSuiteName:@"group.com.AppShareDemo"];
NSString *filePath = [userDefaults valueForKey:@"shareFilePath"];
NSData *data = [NSData dataWithContentsOfFile:filePath];

最关键的一句是,将分享的数据写入分享扩展(AppGroup)中,然后拿到对应存储路径传给宿主APP
注意:以下来自以上网址的内容
You probably call getImageFromExtension from didSelectPost. At the end of didSelectPost you are supposed to call completeRequestReturningItems:completionHandler: to tell the host app to complete the app extension request with an array of result items. When that method is called the whole ShareViewController is dismissed and deallocated. When you call this at the end of didSelectPost, it gets executed before the NSItemProvider could retrieve the image URL. Because that happens asynchronously. To fix this you have to call completeRequestReturningItems:completionHandler: after NSItemProvider has retrieved the imageURL.

Here is how it should work:

  • (void)didSelectPost {
    NSString *typeIdentifier = (NSString *)kUTTypeImage
    NSExtensionItem *item = self.extensionContext.inputItems.firstObject;
    NSItemProvider *itemProvider = item.attachments.firstObject;
    if ([itemProvider hasItemConformingToTypeIdentifier:typeIdentifier]) {
    [itemProvider loadItemForTypeIdentifier:typeIdentifier
    options:nil
    completionHandler:^(NSURL *url, NSError *error) {
    NSURL *imageURL = (NSURL *)item
    self.saveImage(imageURL)
    [self.extensionContext completeRequestReturningItems:@[]
    completionHandler:nil];
    }];
    }
    }
    By the way, there is no need to use dispatch_async when working with NSItemProvider as the provider is already doing his work asynchronously.

I've written a blog post about this, if you want to read a bit more about this.

EDIT

You can now load the image with the file path that you just retrieve. This works only in the extension! If you want to access the image from the containing app you cannot use the file URL you just retrieved. The share extension saves the selected image in a folder that is not accessible by the containing app.

To make the image available to the containing app you have to activate App Groups in you containing app and the extension. Then the extension saves the image to the shared container and the containing app can retrieve it:

func saveImage(url: NSURL) {
guard let imageData = NSData(contentsOfURL: url) else { return }
let selectedImage = UIImage(data: imageData)

let fileManager = NSFileManager.defaultManager()
if let sharedContainer = fileManager.containerURLForSecurityApplicationGroupIdentifier("YOUR_GROUP_IDENTIFIER") {
    if let dirPath = sharedContainer.path {
        let sharedImageFilePath = dirPath + "/image.png"
        let binaryImageData = UIImagePNGRepresentation(selectedImage!)
        binaryImageData?.writeToFile(sharedImageFilePath, atomically: true)
        // send the sharedImageFilePath to the containing app
    }
}

}

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Correctness AdapterViewChildren Summary: AdapterViews can...
    MarcusMa阅读 9,155评论 0赞 6
  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 8,204评论 0赞 10
  • iOS扩展是指?能否列举一些热门或常见的范例? 转自:http://www.cnblogs.com/xdream8...
    JunkieBa阅读 3,984评论 0赞 1
  • 孤獨生長 在曠野或者湖邊 也許只是 被無意選中 但我喜歡這種孤單 Photo by Frederic Lefebvre
    憨憨爹阅读 246评论 0赞 0
  • 日本人生性极其好斗而又非常温和;黩武而又爱美;倨傲自尊而又彬彬有礼;顽梗不化而又柔弱善变;驯服而又不愿接受人摆布;...
    繁榆阅读 754评论 1赞 4

友情链接更多精彩内容