How to use NSURLSession to determine if resource has changed?

后端 未结 2 1989
轮回少年
轮回少年 2020-12-10 00:12

I\'m using NSURLSession to request a JSON resource from an HTTP server. The server uses Cache-Control to limit the time the resource is cached on clients.

This works

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-10 00:44

    This could be done with simple HTTP standard response.

    Assume previous response is something like below:

    { status code: 200, headers {
        "Accept-Ranges" = bytes;
        Connection = "Keep-Alive";
        "Content-Length" = 47616;
        Date = "Thu, 23 Jul 2015 10:47:56 GMT";
        "Keep-Alive" = "timeout=5, max=100";
        "Last-Modified" = "Tue, 07 Jul 2015 11:28:46 GMT";
        Server = Apache;
    } }
    

    Now use below to tell server not to send date if it is not modified since.

    NSURLSession is a configurable container, you would probably need to use http option "IF-Modified-Since"

    Use below configuration kind before downloading the resource,

        NSURLSessionConfiguration *backgroundConfigurationObject = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:@"myBackgroundSessionIdentifier"];
        [backgroundConfigurationObject setHTTPAdditionalHeaders:
         @{@"If-Modified-Since": @"Tue, 07 Jul 2015 11:28:46 GMT"}];
    

    if resource for example doesn't change from above set date then below delegate will be called

        - (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location
        {
    
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) downloadTask.response;
            if([httpResponse statusCode] == 304)
                    //resource is not modified since last download date
        }
    

    Check the downloadTask.response status code is 304 .. then resource is not modified and the resource is not downloaded.

    Note save the previous success full download date in some NSUserDefaults to set it in if-modifed-since

提交回复
热议问题