Search code examples
objective-ciosnsstringnsfilemanager

Is there a better way to check for a newer file than my implementation?


I have an app that downloads PDFs that are updated every few months, and everytime I download a certain PDF, I also download a .txt file which contains one character. Everytime I upload the updated PDF on my server, I also increate the character count in the .txt file on the server by one.

When the user taps the Updates button in my app, I compare the string in the .txt file from the server to the string of the local .txt file.

This is a pretty lightweight way of checking to see if a new PDF is available, but I am asking if there is a better way or lighter way to do this without having to create a .txt file for each PDF file that I have on my server?

Thank you in advance for any help offered!

This is the code I use to check for new PDFs:

NSString *documentDirectory = [(AppDelegate *)[[UIApplication sharedApplication] delegate] applicationDocumentsDirectory];

NSString *path = [documentDirectory stringByAppendingPathComponent:@"test.txt"];

NSString *server = [NSString stringWithContentsOfURL:[NSURL URLWithString:@"foo.com/test.txt"] encoding:NSASCIIStringEncoding error:nil];

NSString *local = [NSString stringWithContentsOfFile:path encoding:NSASCIIStringEncoding error:nil];

if(![local isEqualToString:server])
{
   // I Download the new PDF and the new .txt file here;
   // simple NSURLConnection stuff, no need to elaborate
}

Solution

  • Off the top of my head, the HTTP HEAD method can be used to fetch just the headers rather than the data. If the creation date in the headers is later than the last date you downloaded the data, it's time to fetch a new copy. This can be done with NSURLRequest and NSURLConnection.

    If your server doesn't support the HEAD request or something else prevents its use, you could have a second TXT file with a version/hash/unique identifier in it. Download that instead and compare against the stored value. If it's changed, download the full PDF and save the version text file to disk for reference later.

    If security is an issue and you need to be able to trust the server, use HTTPS in either case.