Search code examples
iosnsurlnsfilemanager

PDF file size from document directory showing zero in iOS


I am retrieving file size of PDF file that located in document directory with following codes.

- (NSString *)sizeOfFile:(NSString *)filePath {
    NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
    NSInteger fileSize = [[fileAttributes objectForKey:NSFileSize] integerValue];
    NSString *fileSizeString = [NSByteCountFormatter stringFromByteCount:fileSize countStyle:NSByteCountFormatterCountStyleFile];
    return fileSizeString;
}



NSURL *url = [self.arrayOfBooks objectAtIndex:indexPath.row];
NSLog(@"%@",[self sizeOfFile:url.absoluteString]); // Showing zero KB.

I am sure there is file in arrayBooks because it can show in cellForRowAtIndexPath.

But i don't know why file size is showing zero.

Please help me.


Solution

  • The most likely cause of your issue is due to an invalid path being sent to sizeOfFile:.

    Your code:

    NSURL *url = [self.arrayOfBooks objectAtIndex:indexPath.row];
    NSLog(@"%@",[self sizeOfFile:url.absoluteString]); // Showing zero KB.
    

    should be:

    NSURL *url = [self.arrayOfBooks objectAtIndex:indexPath.row];
    NSLog(@"%@",[self sizeOfFile:[url path]]);
    

    You want to call the path method to get a file path. absoluteString returns a file URL, not a path.

    Also, don't use property syntax to call methods.