的文件(示例代码))
一直觉得自己写的不是技术而是情怀一个个的教程是自己这一路走来的痕迹。靠专业技能的成功是最具可复制性的希望我的这条路能让你们少走弯路希望我能帮你们抹去知识的蒙尘希望我能帮你们理清知识的脉络希望未来技术之巅上有你们也有我。该封装返回的数据一定要NSData文章目录(推荐)提取文件App中的Zip文件使用测试方法代码效果info.plist的设置使用(不推荐)读取文件App所有文件用tableview显示--学习用效果info.plist的设置代码使用生成json文件保存到文件app读取文件app的json文件进行使用经验相册文件App获取的TIF图片为什么无法加载到地图上(推荐)提取文件App中的Zip文件使用测试方法把想要测试的格式文件直接拖进去icloud云盘就可能测试如果通过隔空投送测试图片很大可能文件会自动放到相册里面代码真正的开发一般都会使用下面的封装通过方法的调用直接返回文件OC-TIFFilePicker(文件App导入TIF图片).zip代码下载效果info.plist的设置keyUISupportsDocumentBrowser/key true/ keyLSSupportsOpeningDocumentsInPlace/key true/使用#import ViewController.h #import Masonry.h #import TIFFilePicker.h interface ViewController () property (nonatomic,strong) UIButton *button; end implementation ViewController - (UIButton *)button { if (!_button) { _button [[UIButton alloc] init]; _button.addTo(self.view); [_button addTarget:self action:selector(buttonTapped:) forControlEvents:UIControlEventTouchUpInside]; [_button setTitle:按钮 forState:UIControlStateNormal]; _button.titleLabel.font [UIFont systemFontOfSize:18]; [_button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal]; _button.backgroundColor [UIColor redColor]; } return _button; } - (void)viewDidLoad { [super viewDidLoad]; self.view.backgroundColor [UIColor whiteColor]; self.button.makeCons(^{ make.center.equal.view(self.view); make.width.height.equal.constants(100); }); } -(void)buttonTapped:(UIButton *)button { [TIFFilePicker tifFilePickerFrom:self completion:^(NSData * _Nullable fileData, NSString * _Nullable fileName, NSError * _Nullable error) { NSLog(fileData: %,fileData); UIImage *selectedImage [UIImage imageWithData:fileData]; }]; } end(不推荐)读取文件App所有文件用tableview显示–学习用下面的例子比较零散你没有经过封装的只是用一下这个功能而已如果想直接调用方法返回文件的话使用上面的方法效果info.plist的设置keyUISupportsDocumentBrowser/key true/ keyLSSupportsOpeningDocumentsInPlace/key true/代码下面的这一份代码是获取文件App中的文件保存到沙盒里面然后从沙盒里面全部获取出来OC- 读取DocumentPicker(iPhone文件App)的文件示例代码本文章实现的效果很简单就是读取iPhone文件App里面的文件保存到沙盒里面然后读取沙盒保存的文件夹然后显示在tableview里面#import FileBrowserViewController.h #import MobileCoreServices/MobileCoreServices.h interface FileBrowserViewController () UIDocumentPickerDelegate, UITableViewDataSource, UITableViewDelegate property (nonatomic, strong) UITableView *tableView; property (nonatomic, strong) NSArray *files; property (nonatomic, strong) NSString *sandboxImportFolderPath; // 专门用于存放导入文件的文件夹路径 end implementation FileBrowserViewController - (void)viewDidLoad { [super viewDidLoad]; // 设置UI [self setupUI]; // 初始化导入文件夹路径 [self setupImportFolder]; // 加载文件列表 [self loadFilesFromImportFolder]; } - (void)setupUI { self.title 文件浏览器; self.view.backgroundColor [UIColor whiteColor]; // 添加导航栏按钮 UIBarButtonItem *importButton [[UIBarButtonItem alloc] initWithTitle:导入文件 style:UIBarButtonItemStylePlain target:self action:selector(importFile)]; self.navigationItem.rightBarButtonItem importButton; // 创建TableView _tableView [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain]; _tableView.delegate self; _tableView.dataSource self; _tableView.tableFooterView [UIView new]; [self.view addSubview:_tableView]; } - (void)setupImportFolder { // 获取Documents目录 NSString *documentsPath [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]; // 创建专门用于存放导入文件的文件夹 _sandboxImportFolderPath [documentsPath stringByAppendingPathComponent:ImportedFiles]; NSFileManager *fileManager [NSFileManager defaultManager]; BOOL isDirectory; // 检查文件夹是否存在不存在则创建 if (![fileManager fileExistsAtPath:_sandboxImportFolderPath isDirectory:isDirectory]) { NSError *error; [fileManager createDirectoryAtPath:_sandboxImportFolderPath withIntermediateDirectories:YES attributes:nil error:error]; if (error) { NSLog(创建导入文件夹失败: %, error.localizedDescription); } else { NSLog(导入文件夹创建成功: %, _sandboxImportFolderPath); } } } - (void)importFile { // 创建文件选择器 UIDocumentPickerViewController *documentPicker [[UIDocumentPickerViewController alloc] initWithDocumentTypes:[(NSString *)kUTTypeItem] inMode:UIDocumentPickerModeOpen]; documentPicker.delegate self; documentPicker.modalPresentationStyle UIModalPresentationFormSheet; [self presentViewController:documentPicker animated:YES completion:nil]; } - (void)loadFilesFromImportFolder { NSFileManager *fileManager [NSFileManager defaultManager]; NSError *error; // 获取导入文件夹中的所有文件 NSArray *contents [fileManager contentsOfDirectoryAtPath:_sandboxImportFolderPath error:error]; if (error) { NSLog(读取文件夹内容失败: %, error.localizedDescription); self.files []; } else { // 过滤掉隐藏文件和文件夹 NSPredicate *predicate [NSPredicate predicateWithFormat:NOT self BEGINSWITH .]; self.files [contents filteredArrayUsingPredicate:predicate]; } [self.tableView reloadData]; } #pragma mark - UIDocumentPickerDelegate - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArrayNSURL * *)urls { // 用户选择了文件 if (urls.count 0) { // 保存文件到导入文件夹 [self saveFilesToImportFolder:urls]; // 重新加载文件列表 [self loadFilesFromImportFolder]; } } - (void)saveFilesToImportFolder:(NSArrayNSURL * *)urls { NSFileManager *fileManager [NSFileManager defaultManager]; for (NSURL *url in urls) { // 检查文件是否可访问 if ([url startAccessingSecurityScopedResource]) { NSFileCoordinator *fileCoordinator [[NSFileCoordinator alloc] init]; NSError *error; [fileCoordinator coordinateReadingItemAtURL:url options:0 error:error byAccessor:^(NSURL *newURL) { // 目标路径 NSString *destinationPath [self.sandboxImportFolderPath stringByAppendingPathComponent:newURL.lastPathComponent]; NSURL *destinationURL [NSURL fileURLWithPath:destinationPath]; // 检查文件是否已存在 if ([fileManager fileExistsAtPath:destinationPath]) { // 如果文件已存在添加时间戳创建新文件名 NSString *fileName [newURL.lastPathComponent stringByDeletingPathExtension]; NSString *fileExtension [newURL.lastPathComponent pathExtension]; NSDateFormatter *formatter [[NSDateFormatter alloc] init]; [formatter setDateFormat:yyyyMMddHHmmss]; NSString *timestamp [formatter stringFromDate:[NSDate date]]; NSString *newFileName [NSString stringWithFormat:%_%.%, fileName, timestamp, fileExtension]; destinationPath [self.sandboxImportFolderPath stringByAppendingPathComponent:newFileName]; destinationURL [NSURL fileURLWithPath:destinationPath]; } // 复制文件 NSError *copyError; BOOL success [fileManager copyItemAtURL:newURL toURL:destinationURL error:copyError]; if (success) { NSLog(文件保存成功: %, destinationPath); } else { NSLog(文件保存失败: %, copyError.localizedDescription); } }]; [url stopAccessingSecurityScopedResource]; } } } #pragma mark - UITableViewDataSource - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.files.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *cellIdentifier FileCell; UITableViewCell *cell [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; if (!cell) { cell [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier]; } cell.textLabel.text self.files[indexPath.row]; cell.accessoryType UITableViewCellAccessoryDisclosureIndicator; return cell; } #pragma mark - UITableViewDelegate - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { [tableView deselectRowAtIndexPath:indexPath animated:YES]; NSString *fileName self.files[indexPath.row]; NSString *filePath [self.sandboxImportFolderPath stringByAppendingPathComponent:fileName]; // 检查文件是否存在 if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) { // 获取文件属性 NSError *attributesError; NSDictionary *attributes [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:attributesError]; if (!attributesError) { NSDate *creationDate [attributes objectForKey:NSFileCreationDate]; NSDate *modificationDate [attributes objectForKey:NSFileModificationDate]; unsigned long long fileSize [[attributes objectForKey:NSFileSize] unsignedLongLongValue]; NSDateFormatter *dateFormatter [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:yyyy-MM-dd HH:mm:ss]; NSString *message [NSString stringWithFormat: 文件名: %\n 大小: %.2f KB\n 创建时间: %\n 修改时间: %, fileName, (double)fileSize / 1024.0, [dateFormatter stringFromDate:creationDate], [dateFormatter stringFromDate:modificationDate]]; UIAlertController *alert [UIAlertController alertControllerWithTitle:文件信息 message:message preferredStyle:UIAlertControllerStyleAlert]; [alert addAction:[UIAlertAction actionWithTitle:确定 style:UIAlertActionStyleDefault handler:nil]]; [self presentViewController:alert animated:YES completion:nil]; } else { UIAlertController *alert [UIAlertController alertControllerWithTitle:文件信息 message:[NSString stringWithFormat:文件名: %, fileName] preferredStyle:UIAlertControllerStyleAlert]; [alert addAction:[UIAlertAction actionWithTitle:确定 style:UIAlertActionStyleDefault handler:nil]]; [self presentViewController:alert animated:YES completion:nil]; } } else { UIAlertController *alert [UIAlertController alertControllerWithTitle:错误 message:文件不存在 preferredStyle:UIAlertControllerStyleAlert]; [alert addAction:[UIAlertAction actionWithTitle:确定 style:UIAlertActionStyleDefault handler:nil]]; [self presentViewController:alert animated:YES completion:nil]; } } end使用-(void)buttonTapped:(UIButton *)button { [self.navigationController pushViewController:[FileBrowserViewController new] animated:YES]; }生成json文件保存到文件app效果info.plist设置keyUISupportsDocumentBrowser/key true/ keyLSSupportsOpeningDocumentsInPlace/key false/ keyNSDocumentsFolderUsageDescription/key string需要访问文件以导入数据/string keyNSDownloadsFolderUsageDescription/key string需要访问下载的文件/string代码-(void)exportClicked:(UIButton *)button{ NSMutableDictionary *addressBookDic [NSMutableDictionary new]; NSMutableArray *list [NSMutableArray new]; for (int i 0; i self.members.count; i) { NSMutableDictionary *dic [NSMutableDictionary new]; [dic setObject:self.members[i].macid ?: forKey:macid]; [dic setObject:self.members[i].mark ?: forKey:mark]; [list addObject:dic]; } [addressBookDic setObject:list forKey:list]; NSString *docPath [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject]; NSString *filePath [docPath stringByAppendingPathComponent:addressBook.json]; NSURL *fileURL [NSURL fileURLWithPath:filePath]; // 转 JSON NSError *error nil; NSData *jsonData [NSJSONSerialization dataWithJSONObject:addressBookDic options:NSJSONWritingPrettyPrinted error:error]; if (error) { NSLog(❌ JSON 序列化失败: %, error); return; } // 写入文件不存在则新建存在则覆盖 BOOL success [jsonData writeToFile:filePath atomically:YES]; if (!success) { NSLog(❌ 写入 JSON 文件失败); return; } // 文件已存在可以安全地打开文档选择器 UIDocumentPickerViewController *picker [[UIDocumentPickerViewController alloc] initWithURLs:[fileURL] inMode:UIDocumentPickerModeExportToService]; picker.modalPresentationStyle UIModalPresentationFullScreen; [self presentViewController:picker animated:YES completion:nil]; }读取文件app的json文件进行使用效果info.plist设置keyUISupportsDocumentBrowser/key true/ keyLSSupportsOpeningDocumentsInPlace/key false/ keyNSDocumentsFolderUsageDescription/key string需要访问文件以导入数据/string keyNSDownloadsFolderUsageDescription/key string需要访问下载的文件/string代码-(void)importClicked:(UIButton *)button{ UIDocumentPickerViewController *picker nil; if (available(iOS 14.0, *)) { picker [[UIDocumentPickerViewController alloc] initForOpeningContentTypes:[UTTypeJSON] asCopy:YES]; // 添加 asCopy:YES } else { picker [[UIDocumentPickerViewController alloc] initWithDocumentTypes:[public.json] inMode:UIDocumentPickerModeImport]; } picker.delegate self; picker.modalPresentationStyle UIModalPresentationFullScreen; [self presentViewController:picker animated:YES completion:nil]; } #pragma mark - UIDocumentPickerDelegate - (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArrayNSURL * *)urls { NSURL *url urls.firstObject; if (!url) return; // 先将文件复制到应用的临时目录 NSFileManager *fileManager [NSFileManager defaultManager]; NSURL *tempDirectory [NSURL fileURLWithPath:NSTemporaryDirectory()]; NSURL *destinationURL [tempDirectory URLByAppendingPathComponent:[url lastPathComponent]]; NSError *error nil; BOOL success [fileManager copyItemAtURL:url toURL:destinationURL error:error]; if (!success) { NSLog(复制文件失败: %, error); return; } // 从临时目录读取文件 NSData *data [NSData dataWithContentsOfURL:destinationURL]; if (!data) { NSLog(读取文件失败); // 清理临时文件 [fileManager removeItemAtURL:destinationURL error:nil]; return; } try { NSDictionary *json [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:error]; if (error) { NSLog(解析 JSON 出错: %, error); return; } NSArray *list json[list]; for (NSDictionary *dic in list) { NSLog(macid: %, mark: %, dic[macid], dic[mark]); } } finally { // 清理临时文件 [fileManager removeItemAtURL:destinationURL error:nil]; } } // 添加处理用户取消选择的情况 - (void)documentPickerWasCancelled:(UIDocumentPickerViewController *)controller { NSLog(用户取消了文件选择); }经验相册文件App获取的TIF图片为什么无法加载到地图上原因是block返回的图片是一个UIImage破坏了TIF图片的特性无法获取经纬度信息需要返回NSData进行还原operator有封装过关于这个问题的解决办法把下面的3个封装复制过来使用