欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

iOS实现两个APP之间共享文件(从一个App拷贝文件至另一个App)

程序员文章站 2022-06-04 19:42:37
...

直接上解决方案:

在项目Info.plist文件中添加如图所示字段(红色框框里是表示所有文件类型都可拷贝)

iOS实现两个APP之间共享文件(从一个App拷贝文件至另一个App)具体文件类型参考:

Apple documentation

到这一步还没完成:

文件拷贝到咱们App了,咱们需要处理一下(要么存本地,要么直接预览)我的处理是存本地.上代码:

- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<NSString*, id> *)options
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths lastObject];
    if (url != nil) {
        NSString *path = [url absoluteString];
        path = [path stringByRemovingPercentEncoding];
        NSMutableString *string = [[NSMutableString alloc] initWithString:path];
        if ([path hasPrefix:@"file:///private"]) {
            [string replaceOccurrencesOfString:@"file:///private" withString:@"" options:NSCaseInsensitiveSearch  range:NSMakeRange(0, path.length)];
        }
        NSArray *tempArray = [string componentsSeparatedByString:@"/"];
        NSString *fileName = tempArray.lastObject;
        NSString *sourceName = options[@"UIApplicationOpenURLOptionsSourceApplicationKey"];
        
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@%@",sourceName,fileName]];
        if ([fileManager fileExistsAtPath:filePath]) {
            NSLog(@"文件已存在");
            [SVProgressHUD showErrorWithStatus:@"文件已存在"];
            return YES;
        }
        [MRTools creatFilePathInManager:sourceName];
        BOOL isSuccess = [fileManager copyItemAtPath:string toPath:filePath error:nil];
        if (isSuccess == YES) {
            NSLog(@"拷贝成功");
            [SVProgressHUD showSuccessWithStatus:@"文件拷贝成功"];
        } else {
            NSLog(@"拷贝失败");
            [SVProgressHUD showErrorWithStatus:@"文件拷贝失败"];
        }
    }
    NSLog(@"application:openURL:options:");
    return  YES;
}

至此结束,大家可以参考下.