Search code examples
iosobjective-cnsfilemanager

Can't download a file in ios


Here is my code to download a book

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{
    NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle]resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:@"Documents"]];

    NSString *filePath= [resourceDocPath stringByAppendingPathComponent:_bookname];//in _bookname i am already  getting the value ,say abcd.pdf

    NSLog(@"The bookfilepath is %@",filePath);

    NSLog(@"the lenght of recieved data is %d", _recievedData.length);//here i get the correct file size also 

    [_recievedData writeToFile:filePath atomically:YES];

    NSFileManager *filemgr;

    filemgr = [NSFileManager defaultManager];

    if ([filemgr fileExistsAtPath: filePath] == YES)
    {
        flag=1;
        NSLog (@"File exists");
    }
    else
    {
        NSLog (@"File not found");  //always this happens in the log
    }
}

No file exists at the filePath. Why? The funny part is _recievedData.length is returning the correct file size.


Solution

  • Because you cannot write into the app bundle ([[NSBundle mainBundle] resourcePath]).

    Write to the documents folder instead.