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

后端 未结 2 1194
感情败类
感情败类 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

    The method below performs a HEAD request to only fetch the header with a Last-Modified field and converts it to NSDate object.

    - (NSDate *)lastModificationDateOfFileAtURL:(NSURL *)url
    {
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
    
        // Set the HTTP method to HEAD to only get the header.
        request.HTTPMethod = @"HEAD";
        NSHTTPURLResponse *response = nil;
        NSError *error = nil;
    
        [NSURLConnection sendSynchronousRequest:request
                              returningResponse:&response
                                          error:&error];
    
        if (error)
        {
            NSLog(@"Error: %@", error.localizedDescription);
            return nil;
        }
        else if([response respondsToSelector:@selector(allHeaderFields)])
        {
            NSDictionary *headerFields = [response allHeaderFields];
            NSString *lastModification = [headerFields objectForKey:@"Last-Modified"];
    
            NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
            [formatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss zzz"];
    
            return [formatter dateFromString:lastModification];
        }
    
        return nil;
    }
    

    You should run this method asynchronously in the background so the main thread is not blocked waiting for the response. This can be easily done using couple of lines of GCD.

    The code below performs a call to fetch the last modification date in a background thread, and call a completion block on the main thread when the date is retrieved.

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^
    {
        // Perform a call on the background thread.
        NSURL *url = [NSURL URLWithString:@"yourFileURL"];
    
        NSDate *lastModifDate = [self lastModificationDateOfFileAtURL:url];
    
        dispatch_async(dispatch_get_main_queue(), ^
        {
            // Do stuff with lastModifDate on the main thread.
        });
    });
    

    I wrote an article about this here:

    Getting last modification date of a file on the server using Objective-C.

提交回复
热议问题