Avoid downloading a file again if it hasn't ch

2020-06-06 02:50发布

问题:

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?

回答1:

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.



回答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.