Search code examples
iosxcodeuiwebviewnsdocumentdirectory

NSMainbundle to NSDocumentsDirectory - Copying a PDF


I was trying to copy an existing pdf file in the NSMainBundle and into the NSDocumentsDirectory. This file is later loaded into the uiwebview. I can't seem to understand why it doesnt copy the file. Any help on this?

 NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory,
                                                     NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSString *resourceDBFolderPath = [[NSBundle mainBundle] pathForResource:@"document" ofType:@"pdf"];


[fileManager copyItemAtPath:resourceDBFolderPath toPath:documentsDirectory error:&error];



NSArray *path1 = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath =  [path1 objectAtIndex:0];
NSString *fileLoc = [basePath stringByAppendingString:@"document.pdf"];
NSURL *url = [NSURL fileURLWithPath:fileLoc];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webview loadRequest:request];

Solution

  • Replace your code source with the following:

    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains( NSDocumentDirectory,
                                                         NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *documentDirectoryPath = [documentsDirectory stringByAppendingPathComponent:@"document.pdf"];
    NSString *resourceDBBundlePath = [[NSBundle mainBundle] pathForResource:@"document" ofType:@"pdf"];
    
    [fileManager copyItemAtPath:resourceDBBundlePath toPath:documentDirectoryPath error:&error];
    

    As mentioned by FD_ Your destination path need to include your file name.