iphone - 将文件下载到 iPhone 中的文件夹

标签 iphone ios ipad nsfilemanager nsdocumentdirectory

我是 iPhone 新手,

我制作了一个应用程序,当用户下载任何东西时,它会被下载到 DocumentDirectory

我想在我在 DocumentDirectory 中创建的文件夹中下载

如何实现?

我想我会将文件下载到我的 DocumentDirectory,然后将该文件移动到我在 DocumentDirectory 中的文件夹。

这是好的做法吗?

这是我的代码片段,但我仍然无法移动我的文件。

- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {

    NSString *file = [NSString stringWithString:[url absoluteString]];
    NSURL *fileURL = [NSURL URLWithString:file];

    NSURLRequest *req = [NSURLRequest requestWithURL:fileURL];
    [NSURLConnection connectionWithRequest:req delegate:self];


    NSString *DestPath=[[[SourcePath stringByAppendingString:@"/"]stringByAppendingString:BookCateg]stringByAppendingString:@"/"];

                   if ([fm copyItemAtPath:SourcePath toPath:DestPath error:&error]) 
                   {
                      NSLog(@"Success !");
                   }
                  else{
                      NSLog(@"Fail to Move!");
                   }

}

我的日志显示 Fail to Move!

我们将不胜感激。

最佳答案

您应该直接将文件下载到文档目录的文件夹中,为此您需要按照@iPhone Developer 的建议创建目录并在该目录中写入文件

例如:

  NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:@"/File"];
  error = nil;
  if (![[NSFileManager defaultManager] fileExistsAtPath:stringPath])
    [[NSFileManager defaultManager] createDirectoryAtPath:stringPath withIntermediateDirectories:NO attributes:nil error:&error];

  NSURL *url = [NSURL URLWithString:@"http://www.ndqatar.mobi/18December/admin/rington/133/QatarDay13.mp3"];
  NSData *data = [NSData dataWithContentsOfURL:url];
  if(data)
  {
    stringPath = [stringPath stringByAppendingPathComponent:[url lastPathComponent]];
    [data writeToFile:stringPath atomically:YES];
  }

如果你想你可以像这样移动文件:

 NSString *destPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:@"/Dest"];
  error = nil;
  if (![[NSFileManager defaultManager] fileExistsAtPath:destPath])
    [[NSFileManager defaultManager] createDirectoryAtPath:destPath withIntermediateDirectories:NO attributes:nil error:&error];
  destPath = [destPath stringByAppendingPathComponent:[stringPath lastPathComponent];];

 [[NSFileManager defaultManager] copyItemAtPath:stringPath toPath:destPath error:&error];

关于iphone - 将文件下载到 iPhone 中的文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11644013/

相关文章:

iphone - html5音频标签在加载音频时播放音频

ios - 如何创建 UIView 弹跳动画?

ios - 在 iOS 项目中包含 C 库

iphone - 使用 @ 作为 NSDictionary 字符串中键的一部分

iphone - 在 CGPath 之间着色

iPhone - 如何找到它所指的对象?

iphone - UIAlertView 开始显示,屏幕变暗,但直到为时已晚才弹出!

iphone - iOS图像比较

objective-c - presentModalViewController 无法在已越狱的 iOs 4.0.1 设备上运行

iphone - 从预览内容生成的文档缩略图