3

I need to download an XML file, using HTTP protocol, to use it locally on my iPhone app. Occasionally this file will be updated on the server, but not very often.

How do I compare the already downloaded file that is already in the Documents folder, with the one on the server, just downloading it if the content has been updated on the server?

Rob
  • 415,655
  • 72
  • 787
  • 1,044
neowinston
  • 7,584
  • 10
  • 52
  • 83

2 Answers2

12

The first time you download the file, save the date from the Last-Modified header of the response. You can pull it out of the NSHTTPURLResponse object.

On subsequent runs, put that date in the If-Modified-Since header of the NSURLRequest. If the file on the server hasn't changed, the statusCode of the NSHTTPURLResponse should be 304 (which means “Not Modified”) and the body of the response should be empty.

rob mayoff
  • 375,296
  • 67
  • 796
  • 848
  • Beautiful. Much more efficient than my solution. – CodaFi Apr 09 '12 at 04:36
  • Thanks Rob, I'll try that. Can I verify it not only by date, but also including the time? – neowinston Apr 09 '12 at 04:37
  • An HTTP date includes the time, and is in a very specific format. The headers are defined in [section 14 of the HTTP 1.1 spec](http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html). The date format is defined in [section 3.3.1](http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1). – rob mayoff Apr 09 '12 at 04:39
  • It will probably be easiest for you to just treat the date as an opaque string that you copy out of the `Last-Modified` header, save in `NSUserDefaults`, and copy into the `If-Modified-Since` header, without trying to parse it. – rob mayoff Apr 09 '12 at 04:40
  • Wonderful! Thanks a lot, I'll try it and let you know the results! – neowinston Apr 09 '12 at 04:43
2

If you want to traverse the documents directory to look for a specifically named file, use NSFileManager's -fileExistsAtPath:isDirectory and compare it to the name of the downloaded file (-suggestedFilename as long as you are using NSURLResponse) with -isEqualToString.

If you need to get a revision date, use NSFileManager's -attributesOfItemAtPath:error: in conjunction with the key NSFileModificationDate.

CodaFi
  • 43,043
  • 8
  • 107
  • 153
  • The file name would be the same, but if the contant is the same too? Will I have to download it again, with both files being exactly the same? – neowinston Apr 09 '12 at 04:33
  • Checking their contents would involve downloading it to a temp directory and checking. I've posted the way to get a modification date; though my knowledge of HTTP requests is quite limited. Is there a way to get the modification date from the HTTP header? – CodaFi Apr 09 '12 at 04:35