How to query the last modification date of a file via HTTP on the iPhone using NSHTTPURLResponse?

后端 未结 2 1192
感情败类
感情败类 2021-02-09 14:32

In my iPhone application I need to query the last modification date of an internet .m4a file via HTTP, but I DON\'T want to downloadin

2条回答
  •  [愿得一人]
    2021-02-09 15:16

    This answer assumes your server supports it, but what you do is send a "HEAD" request to the file URL and you get back just the file headers. You can then inspect the header called "Last-Modified" which normally has the date format @"EEE',' dd MMM yyyy HH':'mm':'ss 'GMT'".

    Here's some code:

    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"HEAD"];
    NSHTTPURLResponse *response;
    [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
    if ([response respondsToSelector:@selector(allHeaderFields)]) 
    {
      NSDictionary *dictionary = [response allHeaderFields];
      NSString *lastUpdated = [dictionary valueForKey:@"Last-Modified"];
      NSDate *lastUpdatedServer = [fileDateFormatter dateFromString:lastUpdated];
    
      if (([localCreateDate earlierDate:lastUpdatedServer] == localCreateDate) && lastUpdatedServer) 
      {
        NSLog(@"local file is outdated: %@ ", localPath);
        isLatest = NO;
      } else {
        NSLog(@"local file is current: %@ ", localPath);
      }
    
    } else {
      NSLog(@"Failed to get server response headers");
    }
    

    Of course, you probably want this to be done asynchronously in the background, but this code should point you in the right direction.

    Best Regards.

提交回复
热议问题