iosnsxmlparserinitwithcontentsofurl

iOS Check if remote file has updates before downloading


This is a two part question. I am using NSXMLParser to download an RSS feed.

NSURL *url = [NSURL URLWithString:@"linktorssxml"];
parser = [[NSXMLParser alloc] initWithContentsOfURL:url];
[parser setDelegate:self];
[parser setShouldResolveExternalEntities:NO];
[parser parse];

I wondered if there is a way to simply read the header of the xml remotely and check the last update timestamp, so that I only need to run the parser code and actually pull the entire xml if there has been a change?

Further, as I said this is a two part question. I have the same thought with a plist that is hosted externally. This is currently called as follows:-

_content = [[NSArray alloc] initWithContentsOfURL:[NSURL URLWithString:@"pathto.plist"]];

Again, is there a way of checking the header for last update time remotely, and thus only downloading the full file if there has been a change?


Solution

  • Yes, but you need to use NSURLConnection or NSURLSession to download the data instead of asking NSXMLParser to do it for you.

    You can get the HTTP headers (which probably include a last modified date) by using an NSMutableURLRequest to describe what you want. That has a method named setHTTPMethod:, and you can set the method to HEAD. Make the connection, get the headers, and decide what to do next.

    Unless the XML is very large though, that's probably not the most effective approach. If the file has been modified, you'll just need to make a second network request to get it. Network requests are slow, so you should keep them to a minimum. In most cases you'd be better off using NSURLConnection or NSURLSession to just get the file. The response will include the HTTP headers, so you still get the date, and you can still decide whether or not to run the parser.