If-Modified-Since header

HI,


I'm trying to get files recently modified on a server. I use for that the If-Modified-Since HTTP header, and the server send correct respons with 304 (not modified) status.

On the iOS device, I get no error and empty data.

Here is the method I use:


- (void)getContentOfURL:(NSString*)url ifModifiedSince:(NSString*)sinceDate completionBlock:(DataWebServiceCompletionBlock)completionBlock {

NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url]

cachePolicy:NSURLRequestReloadIgnoringLocalCacheData // NSURLRequestReloadIgnoringLocalCacheData / NSURLRequestUseProtocolCachePolicy

timeoutInterval:10.0];

[request setHTTPMethod: @"GET"];

[request setValue:sinceDate forHTTPHeaderField:@"If-Modified-Since"]; // http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html


NSURLSessionDataTask * task = [[NSURLSession sharedSession] dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {

dispatch_async(dispatch_get_main_queue(), ^{

if (completionBlock) {

completionBlock(data, error); // the server send 304 status, but I get error == nil and data.lenght = 0

}

});

}];


[task resume];

}


Any idea ?

This is the expected behaviour when using the If-Modified-Since HTTP header and there is no new data on the server: error variable is nil because the task has been completed succesfully, the data variable is nil because the server will not return any data, only HTTP headers with the 304 status.

To extend elemans’s response…

In the NSURLSession API NSError values are reserved for transport errors, that is, problems sending the request to or getting the response from the server. To see the HTTP status returned by the server, cast the NSURLResponse to an NSHTTPURLResponse and look at its

statusCode
property. Here’s an example of how I usually do this (sorry it’s in Swift, that’s just what I had lying around):
let request = URLRequest(url: self.url)
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
    if let error = error {
        … transport error …
    } else {
        let response = response as! HTTPURLResponse
        let data = data!
        if response.statusCode != 200 {
            … unexpected HTTP status …
        } else if response.mimeType != "application/json" {
            … unexpected response type …
        } else {
            … we're good to go …
        }
    } 
}
task.resume()

Share and Enjoy

Quinn “The Eskimo!”
Apple Developer Relations, Developer Technical Support, Core OS/Hardware

let myEmail = "eskimo" + "1" + "@apple.com"

WWDC runs Mon, 5 Jun through to Fri, 9 Jun. During that time all of DTS will be at the conference, helping folks out face-to-face. http://developer.apple.com/wwdc/

If-Modified-Since header
 
 
Q