iOS 文件下载到手机

当服务器传来的文件,需要下载到手机指定文件夹,有两种情况:

一、文件是以base64或者data的形式:

1. 调起UIDocumentPickerViewController
- (void)downloadFileToApp:(NSDictionary *)dic
{
    NSString *fileDataStr = dic[@"dataStr"];
    NSData *decodData = [[NSData alloc] initWithBase64EncodedString: fileDataStr options:NSDataBase64DecodingIgnoreUnknownCharacters];
    NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
    NSString *fileName = [NSString stringWithFormat:@"/%@.%@", dic[@"name"], dic[@"type"]];
    NSString *signDirec = [documentsDirectory stringByAppendingString:fileName];
    
    /// 保存文件到沙盒
    BOOL downResult = [decodedIData writeToFile: signDirec atomically:YES];
    if (downResult) {
        UIDocumentPickerViewController *documentPickerVC = [[UIDocumentPickerViewController alloc] initWithURL:[NSURL fileURLWithPath: signDirec] inMode:UIDocumentPickerModeExportToService];
        documentPickerVC.delegate = self;
        documentPickerVC.modalPresentationStyle = UIModalPresentationFormSheet;
        [self presentViewController:documentPickerVC animated:YES completion:nil];
    }else{
        //文件名有误,存储失败
    }
}
2.实现 UIDocumentPickerViewController的delegate
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentsAtURLs:(NSArray *)urls
{
    // 获取授权
    BOOL fileAut = [urls.firstObject startAccessingSecurityScopedResource];
    if (fileAut) {
        // 通过文件协调工具来得到新的文件地址  
        NSFileCoordinator *fileCoordinator = [[NSFileCoordinator alloc] init];
        NSError *error;
        [fileCoordinator coordinateReadingItemAtURL:urls.firstObject options:0 error:&error byAccessor:^(NSURL *newURL) {
            //文件存储成功
         }];
        [urls.firstObject stopAccessingSecurityScopedResource];
    } else {
        //授权失败
     }
}

二、文件是以http://xxxxxxx.pdf的形式:

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    if([message.name isEqualToString:@"dowloadThisFile"]){
     //这里需要跟网页交互,需跟web协调传值方法
     [[UIApplication sharedApplication] openURL:[NSURL URLWithString:message.body]];
}
}

你可能感兴趣的:(iOS 文件下载到手机)