iOS從系統(tǒng)“文件管理”APP選擇文件上傳以及保存文件到“文件”APP

一、從系統(tǒng)“文件”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 支持的文件類型數(shù)組
 "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];
        // 設(shè)置代理
        _documentPickerVC.delegate = self;
        // 設(shè)置模態(tài)彈出方式
        _documentPickerVC.modalPresentationStyle = UIModalPresentationFormSheet;
    }
    return _documentPickerVC;
}
 
#pragma mark - UIDocumentPickerDelegate
 
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray<NSURL *> *)urls {
    // 獲取授權(quán)
    BOOL fileUrlAuthozied = [urls.firstObject startAccessingSecurityScopedResource];
    if (fileUrlAuthozied) {
        // 通過文件協(xié)調(diào)工具來得到新的文件地址,以此得到文件保護(hù)功能
        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) {
                // 讀取出錯(cuò)
            } else {
                // 上傳
                NSLog(@"fileName : %@", fileName);
                // [self uploadingWithFileData:fileData fileName:fileName fileURL:newURL];
            }
            [self dismissViewControllerAnimated:YES completion:NULL];
        }];
        [urls.firstObject stopAccessingSecurityScopedResource];
    } else {
        // 授權(quán)失敗
    }
}
 
@end

二、從開發(fā)APP中保存文件到系統(tǒng)“文件”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:@"下載文件要求手機(jī)系統(tǒng)版本在11.0以上"];
        return;
    }
    /**
    /// 保存網(wǎng)絡(luò)文件到沙盒一
    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];
    */
    /// 保存網(wǎng)絡(luò)文件到沙盒二
    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];
        // 設(shè)置代理
        documentPickerVC.delegate = self;
        // 設(shè)置模態(tài)彈出方式
        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];
    // 判斷是否存在,不存在則創(chuàng)建
    NSFileManager *fileManager = [NSFileManager defaultManager];
    // fileExistsAtPath 判斷一個(gè)文件或目錄是否有效,isDirectory判斷是否一個(gè)目錄
    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 {
    // 獲取授權(quán)
    BOOL fileUrlAuthozied = [urls.firstObject startAccessingSecurityScopedResource];
    if (fileUrlAuthozied) {
        // 通過文件協(xié)調(diào)工具來得到新的文件地址,以此得到文件保護(hù)功能
        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) {
                // 讀取出錯(cuò)
            } else {
                // 上傳
                NSLog(@"fileName : %@", fileName);
            }
        }];
        [urls.firstObject stopAccessingSecurityScopedResource];
    } else {
        // 授權(quán)失敗
    }
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 上傳文件到服務(wù)器是一個(gè)常用的操作,而在服務(wù)器上保存文件就需要多多用心了。因?yàn)槟悴豢赡苤辉谝粋€(gè)路徑里保存文件,所以需...
    厚土火焱閱讀 2,129評(píng)論 2 0
  • 1.什么是FastDFS? FastDFS是用c語言編寫的一款開源的分布式文件系統(tǒng)。FastDFS為互聯(lián)網(wǎng)量身定制...
    中庸逍遙閱讀 1,494評(píng)論 0 2
  • 概述 一說到文件上傳,想必大家都并不陌生,更何況是利用AFNetworking(PS:后期統(tǒng)稱AF)來做,那更是小...
    CoderMikeHe閱讀 13,854評(píng)論 48 134
  • 久違的晴天,家長(zhǎng)會(huì)。 家長(zhǎng)大會(huì)開好到教室時(shí),離放學(xué)已經(jīng)沒多少時(shí)間了。班主任說已經(jīng)安排了三個(gè)家長(zhǎng)分享經(jīng)驗(yàn)。 放學(xué)鈴聲...
    飄雪兒5閱讀 7,788評(píng)論 16 22
  • 今天感恩節(jié)哎,感謝一直在我身邊的親朋好友。感恩相遇!感恩不離不棄。 中午開了第一次的黨會(huì),身份的轉(zhuǎn)變要...
    余生動(dòng)聽閱讀 10,798評(píng)論 0 11

友情鏈接更多精彩內(nèi)容