Search code examples
iphoneiosipadnsfilemanagernsdocumentdirectory

Download file to Folder in iPhone


I am new to iPhone,

I made app in which, when user downloads anything it gets downloaded into DocumentDirectory

I wants downloading inside my folder which i have created in DocumentDirectory

How to achieve this ?

I thought I will download file to my DocumentDirectory and i will move that file to my folder inside DocumentDirectory.

Is it good practice ?

Here is my code snippet, But still i am unable to move my file.

- (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!");
                   }

}

My log shows Fail to Move!

Any help will be appreciated.


Solution

  • You should directly download file to folder of document directory and for that u need to create directory as @iPhone Developer suggested and write file in that directory

    For example:

      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];
      }
    

    If u want u can move file like this:

     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];