How to get Remote File Last-Modification Date

筅森魡賤 提交于 2019-12-01 07:07:30

问题


I need to get the file modification date of a remote file.

Obviously, attributes in this example returns NULL:

- (BOOL) fileHasBeenModifiedSinceLastLaunch
{
    NSError * err = nil;
    NSDictionary * attributes = [FILEMANAGER attributesOfItemAtPath:[NSURL URLWithString:@"http://www.wrightscs.com/some_file.txt"] error:&err];
    NSString * modified = [NSString stringWithFormat:@"%@",[attributes objectForKey:@"NSFileModificationDate"]];
    NSString * savedmod = [[NSUserDefaults standardUserDefaults] objectForKey:@"kFeedLastModified"];

    NSLog(@"Error: %@",[err localizedDescription]);
    NSLog(@"Saved Modified Date: %@", savedmod);
    NSLog(@"Last  Modified Date: %@", modified);

    [[NSUserDefaults standardUserDefaults] setObject:modified forKey:@"kFeedLastModified"];
    [[NSUserDefaults standardUserDefaults] synchronize];

    if ( [savedmod isEqualToString:modified] )
    {
        NSLog(@"File has not been modified.");
        return NO; 
    } else 
    {
        NSLog(@"File has been modified.");
        return YES;
    }    
}

Output:

2011-08-01 01:25:51.088 WrightsCS[2858:903] Error: The file “some_file.txt” couldn’t be opened because there is no such file.
2011-08-01 01:25:51.092 WrightsCS[2858:903] Saved Modified Date: (null)
2011-08-01 01:25:51.093 WrightsCS[2858:903] Last  Modified Date: (null)
2011-08-01 01:25:51.095 WrightsCS[2858:903] Feed has not been modified.

回答1:


So I was able to figure it out.

You can use NSURLConnection and NSURLRequest to get the http headers of the file, then you can look for the key Last-Modified:

- (void) sendRequestForLastModifiedHeaders
{
    /*  send a request for file modification date  */
    NSURLRequest *modReq = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.wrightscs.com/some_file.txt"]
                                            cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0f];
    [[NSURLConnection alloc] initWithRequest:modReq delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{
    /*  convert response into an NSHTTPURLResponse, 
        call the allHeaderFields property, then get the
        Last-Modified key.
     */
    NSString * last_modified = [NSString stringWithFormat:@"%@",
                                                      [[(NSHTTPURLResponse *)response allHeaderFields] objectForKey:@"Last-Modified"]

    NSLog(@"Last-Modified: %@", last_modified );
} 


来源:https://stackoverflow.com/questions/6895451/how-to-get-remote-file-last-modification-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!