根据url地址下载文件到本地,返回本地文件地址

妖狐艹你老母 2023-10-18 15:27 224阅读 0赞
  1. -(NSString*)DownloadTextFile:(NSString*)fileUrl fileName:(NSString*)_fileName
  2. {
  3. NSString *sandboxPath = NSHomeDirectory();
  4. NSString *documentPath = [sandboxPath stringByAppendingPathComponent:@"Documents"];//将Documents添加到sandbox路径上
  5. NSString *FileName=[documentPath stringByAppendingPathComponent:_fileName];//fileName就是保存文件的文件名
  6. NSFileManager *fileManager = [NSFileManager defaultManager];
  7. if ([fileManager fileExistsAtPath:FileName])
  8. {
  9. return FileName;
  10. }else
  11. {
  12. NSURL *url = [NSURL URLWithString:fileUrl];
  13. NSLog(fileUrl);
  14. NSData *data = [NSData dataWithContentsOfURL:url];
  15. [data writeToFile:FileName atomically:YES];//将NSData类型对象data写入文件,文件名为FileName
  16. }
  17. return FileName;
  18. }

/打开本地文件,获取文件路径

  1. NSString *FileName = @"myWebURL.plist";
  2. NSArray *cachePath= NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
  3. NSString *cacheDir = [cachePath objectAtIndex:0];
  4. NSString *FilePath = [cacheDir stringByAppendingPathComponent:FileName];
  5. NSFileManager *fileManager = [NSFileManager defaultManager];
  6. // Copy the file from the resourcepath to the documentpath
  7. if (![fileManager fileExistsAtPath:FilePath])
  8. {
  9. NSString *filePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:FileName];
  10. NSError *error;
  11. [fileManager copyItemAtPath:filePathFromApp toPath:FilePath error:&error];
  12. }
  13. NSLog(FilePath);

发表评论

表情:
评论列表 (有 0 条评论,224人围观)

还没有评论,来说两句吧...

相关阅读