1保存至本APP
需要实现在AppDelegate文件中实现方法
- (BOOL)application:(UIApplication )app openURL:(NSURL )url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options,然后在这个方法中获取文件的具体信息并保存至当前APP,后续就可以查询并使用文件。
-(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options{
//打开“文件”应用中的文件 需要实现的方法
NSString *UIApplicationOpenURLOptionsOpenInPlaceKey = [NSString stringWithFormat:@"%@",options[@"UIApplicationOpenURLOptionsOpenInPlaceKey"]];
if([UIApplicationOpenURLOptionsOpenInPlaceKey isEqualToString:@"1"]){
NSLog(@"本app文件");
}else{
NSLog(@"非----本app文件");
/**
非----本app文件
需要自动保存到app内
*/
NSString *pathDocuments = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *imagePath = [NSString stringWithFormat:@"%@", pathDocuments];
imagePath = [imagePath stringByAppendingString:@"/"];
[[NSFileManager defaultManager] createDirectoryAtPath:imagePath withIntermediateDirectories:YES attributes:nil error:nil];
NSString *fileName_Save = [[NSString stringWithFormat:@"%@",url] componentsSeparatedByString:@"/"].lastObject;
fileName_Save = [fileName_Save stringByRemovingPercentEncoding];
NSString *filePath = [imagePath stringByAppendingPathComponent:fileName_Save];
[[NSFileManager defaultManager] removeItemAtPath:filePath error:nil];
NSData *wirteData = [NSData dataWithContentsOfURL:url];
BOOL isSuccess = [wirteData writeToFile:filePath atomically:YES];
if (isSuccess) {
NSLog(@"******能写进去");
NSString *locationPath = [NSString stringWithFormat:@"保存成功,位置为:文件/我的iPhone/%@/%@",APPNAME,fileName_Save];
}else{
NSLog(@"*******不能写进去 文件拷贝失败,请重试!");
}
}
return YES;
}
2 查找文件并使用
NSString *pathDocuments = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *imagePath = [NSString stringWithFormat:@"%@/", pathDocuments];
NSArray *fileList = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:imagePath error:nil];
NSMutableArray *fileFolderArr = [[NSMutableArray alloc] init];//文件夹
NSMutableArray *fileArr = [[NSMutableArray alloc] init];//文件
BOOL isFileFolder = NO;
//在上面那段程序中获得的fileList中列出文件夹名
for (NSString *file in fileList) {
NSString *path = [imagePath stringByAppendingPathComponent:file];
//判断是否存在并且是否是文件夹isFileFolder
[[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:(&isFileFolder)];
if (isFileFolder) {
[fileFolderArr addObject:@{@"fileName":file,@"filePath":path}];
}else{
[fileArr addObject:@{@"fileName":file,@"filePath":path}];
}
isFileFolder = NO;
}
NSLog(@"所有文件:%@",fileArr);
NSLog(@"所有文件夹:%@",fileFolderArr);