美文网首页
iOS 系统 "文件管理" 写入和读取文件记录

iOS 系统 "文件管理" 写入和读取文件记录

作者: 小緈福 | 来源:发表于2021-07-22 10:29 被阅读0次

一、从系统“文件”APP选择文件上传

#import "ViewController.h"
 
@interface ViewController () <UIDocumentPickerDelegate>
 
@property (nonatomic, strong) UIDocumentPickerViewController *documentPickerVC;
 
@end
 
@implementation ViewController
 
- (void)viewDidLoad {
    [super viewDidLoad];
}
 
- (IBAction)tapSelectFileAction:(id)sender {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.35 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self presentViewController:self.documentPickerVC animated:YES completion:nil];
    });
}
 
/**
 初始化 UIDocumentPickerViewController
 
 @param allowedUTIs 支持的文件类型数组
 "public.content",
 "public.text",
 "public.source-code",
 "public.image",
 "public.audiovisual-content",
 "com.adobe.pdf",
 "com.apple.keynote.key",
 "com.microsoft.word.doc",
 "com.microsoft.excel.xls",
 "com.microsoft.powerpoint.ppt"
 @param mode 支持的共享模式
 */
- (UIDocumentPickerViewController *)documentPickerVC {
    if (!_documentPickerVC) {
        NSArray *types = @[@"public.content",@"public.text"];
        self.documentPickerVC = [[UIDocumentPickerViewController alloc] initWithDocumentTypes:types inMode:UIDocumentPickerModeOpen];
        // 设置代理
        _documentPickerVC.delegate = self;
        // 设置模态弹出方式
        _documentPickerVC.modalPresentationStyle = UIModalPresentationFormSheet;
    }
    return _documentPickerVC;
}
 
#pragma mark - UIDocumentPickerDelegate
 
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls {
    // 获取授权
    BOOL fileUrlAuthozied = [urls.firstObject startAccessingSecurityScopedResource];
    if (fileUrlAuthozied) {
        // 通过文件协调工具来得到新的文件地址,以此得到文件保护功能
        NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] init];
        NSError *error;
        
        [fileCoordinator coordinateReadingItemAtURL:urls.firstObject options:0 error:&error byAccessor:^(NSURL *newURL) {
            // 读取文件
            NSString *fileName = [newURL lastPathComponent];
            NSError *error = nil;
            NSData *fileData = [NSData dataWithContentsOfURL:newURL options:NSDataReadingMappedIfSafe error:&error];
            if (error) {
                // 读取出错
            } else {
                // 上传
                NSLog(@"fileName : %@", fileName);
                // [self uploadingWithFileData:fileData fileName:fileName fileURL:newURL];
            }
            [self dismissViewControllerAnimated:YES completion:NULL];
        }];
        [urls.firstObject stopAccessingSecurityScopedResource];
    } else {
        // 授权失败
    }
}
 
@end

二、从开发APP中保存文件到系统“文件”APP

#pragma mark - 下载文件
/// http://jadinec-test.oss-accelerate.aliyuncs.com/excelFile/a5f23e130d5e4dd7adda942c45207927.pdf
- (void)downLoadWithFilePath:(NSString *)filePath {
    float version = [[[UIDevice currentDevice] systemVersion] floatValue];
    if (version >= 11) {
        
    } else {
        [MBProgressHUD showError:@"下载文件要求手机系统版本在11.0以上"];
        return;
    }
    /**
    /// 保存网络文件到沙盒一
    NSURLRequest *req = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:filePath]];
    NSData *fileData = [NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil];
    NSString *temp = NSTemporaryDirectory();
    NSFileManager *fm = [NSFileManager defaultManager];
    NSString *fullPath = [self getNativeFilePath:[filePath componentsSeparatedByString:@"/"].lastObject];
    BOOL downResult = [fm createFileAtPath:fullPath contents:fileData attributes:nil];
    */
    /// 保存网络文件到沙盒二
    NSData *fileData = [NSData dataWithContentsOfURL:[NSURL URLWithString:filePath]];
    NSString *fullPath = [self getNativeFilePath:[filePath componentsSeparatedByString:@"/"].lastObject];
    BOOL downResult = [fileData writeToFile:fullPath atomically:YES];
    
    if (downResult) {
        UIDocumentPickerViewController *documentPickerVC = [[UIDocumentPickerViewController alloc] initWithURL:[NSURL fileURLWithPath:fullPath] inMode:UIDocumentPickerModeExportToService];
        // 设置代理
        documentPickerVC.delegate = self;
        // 设置模态弹出方式
        documentPickerVC.modalPresentationStyle = UIModalPresentationFormSheet;
        [self.navigationController presentViewController:documentPickerVC animated:YES completion:nil];
    }
}
 
// 获得文件沙盒地址
- (NSString *)getNativeFilePath:(NSString *)fileName {
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *munu = [NSString stringWithFormat:@"%@/%@",@"downLoad",fileName];
    NSString *filePath = [path stringByAppendingPathComponent:munu];
    // 判断是否存在,不存在则创建
    NSFileManager *fileManager = [NSFileManager defaultManager];
    // fileExistsAtPath 判断一个文件或目录是否有效,isDirectory判断是否一个目录
    BOOL isDir = NO;
    NSMutableArray *theArr = [[filePath componentsSeparatedByString:@"/"] mutableCopy];
    [theArr removeLastObject];
    NSString *thePath = [theArr componentsJoinedByString:@"/"];
    BOOL existed = [fileManager fileExistsAtPath:thePath isDirectory:&isDir];
    if ( !(isDir == YES && existed == YES) ) { // 如果文件夹不存在
        [fileManager createDirectoryAtPath:thePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return filePath;
}
 
#pragma mark - UIDocumentPickerDelegate
 
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls {
    // 获取授权
    BOOL fileUrlAuthozied = [urls.firstObject startAccessingSecurityScopedResource];
    if (fileUrlAuthozied) {
        // 通过文件协调工具来得到新的文件地址,以此得到文件保护功能
        NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] init];
        NSError *error;
        
        [fileCoordinator coordinateReadingItemAtURL:urls.firstObject options:0 error:&error byAccessor:^(NSURL *newURL) {
            // 读取文件
            NSString *fileName = [newURL lastPathComponent];
            NSError *error = nil;
            //NSData *fileData = [NSData dataWithContentsOfURL:newURL options:NSDataReadingMappedIfSafe error:&error];
            if (error) {
                // 读取出错
            } else {
                // 上传
                NSLog(@"fileName : %@", fileName);
            }
        }];
        [urls.firstObject stopAccessingSecurityScopedResource];
    } else {
        // 授权失败
    }
}

作者邮件:zhangxmsy@163.com, 有问题联系。

相关文章

  • iOS 系统 "文件管理" 写入和读取文件记录

    一、从系统“文件”APP选择文件上传 二、从开发APP中保存文件到系统“文件”APP 作者邮件:zhangxmsy...

  • fs文件系统操作

    基础写入文件 简单写入文件 流式文件写入 简单文件读取 流式文件读取 流式文件拷贝(读取 + 写入) 复制文件 f...

  • 从零开始学习Hbuilder(三)

    1. IO模块管理本地文件系统 用于对文件系统的目录浏览、文件的读取、文件的写入等操作 1.1 resolveLo...

  • yaml 文件管理

    yaml文件管理,包括读取yaml文件内容,写入yaml文件,清空yaml文件。

  • python 文件操作

    fp=open("文件路径","方式") 文件读取 文件写入 文件关闭 文件读取写入方式

  • IOS文件管理

    iOS开发-文件管理(一) 一、iOS中的沙盒机制 iOS应用程序只能对自己创建的文件系统读取文件,这个独立、封闭...

  • iOS文件管理

    iOS开发-文件管理(一) 一、iOS中的沙盒机制 iOS应用程序只能对自己创建的文件系统读取文件,这个独立、封闭...

  • txt读写

    文件打开 读文件 读取字符串 按行读取整个文件 写文件 字符串写入txt 列表写入文件 双层列表写入文件 数组写入文件

  • Python中txt的简单操作

    Python操作txt文件的基础操作记录,包含新建文件、读取文件、写入文件、替换文件、修改文件后缀和插入数据。1....

  • nodeJS读取json文件并写入txt或redis中

    【1:读取json写入txt文件】json文件book.json js文件 【2:读取json写入redis文件/...

网友评论

      本文标题:iOS 系统 "文件管理" 写入和读取文件记录

      本文链接:https://www.haomeiwen.com/subject/queemltx.html