Search code examples
iosobjective-cuidocumentpickerviewcontroller

How to check the PDF size before uploading in iOS?


I have a requirement of uploading PDF file which is not more than 2 MB. Right now I am using the UIDocumentPickerViewController to browse the PDF files. Is there any way to check whether the PDF's size is larger than 2 MB? I am able to get the size using NSByteCountFormatter. The code is given below:

NSData *fileData = [NSData dataWithContentsOfURL:url];
NSLog(@"Byte Length%@", [[NSByteCountFormatter new] stringFromByteCount:fileData.length]);
NSString *twoMB = [[NSByteCountFormatter new] stringFromByteCount:fileData.length];
NSString *allowedmem = @"2 MB";
if (twoMB > allowedmem) {
    NSLog(@"Greater than 2 MB");
} else {
    ViewMyPDFViewController *webview = [[ViewMyPDFViewController alloc]init];
    webview.productURL = url;
    [self presentViewController:webview animated:YES completion:nil];
}

I have tried this code but it is not working well in the if condition. Please tell what I am doing wrong. How do I check whether it is greater than 2 MB?


Solution

  • You are comparing two strings in this expression inside the if condition:

    twoMB > allowedmem
    

    This is doing an alphabetical comparison rather than a numerical one. In some cases this might happen to give you the correct result anyway (e.g. "3 MB" > "2 MB" => true) but in many cases it wouldn't (e.g. "300 kB" > "2 MB" => true).

    You do not need NSByteCountFormatter as you already have the number of bytes. Simply check if the number of bytes exceeds 2 MB. For example, compare it to 2E6:

    NSData *fileData = [NSData dataWithContentsOfURL:url];
    NSUInteger pdfBytes = fileData.length;
    NSUInteger allowedBytes = 2e6; // 2 MB is 2 million bytes, or 2 x 10 ^ 6
    if (pdfBytes > allowedBytes) {
        NSLog(@"Greater than 2 MB");
    } else {
        ViewMyPDFViewController *webview = [[ViewMyPDFViewController alloc]init];
        webview.productURL = url;
        [self presentViewController:webview animated:YES completion:nil];
    }
    

    Note that these contexts typically use a binary system, so 2 MB is actually 2,097,152 bytes if you want to be more exact. There are more robust methods of comparison involving formatters as you have shown but you should be careful to do a numeric and not an alphabetic comparison regardless of which method you use. You may also find it useful to create a file which you know is 2 MB in size, and get its .length after loading it in, and just using whatever number you get there for the comparison.