【问题标题】:How to get Remote File Last-Modification Date如何获取远程文件的最后修改日期
【发布时间】:2011-10-17 06:00:08
【问题描述】:

我需要获取远程文件的文件修改日期。

显然,attributes 在本例中返回 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;
    }    
}

输出:

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.

【问题讨论】:

    标签: objective-c cocoa nsurl nsfilemanager


    【解决方案1】:

    所以我能够弄清楚。

    您可以使用NSURLConnectionNSURLRequest获取文件的http头,然后您可以查找关键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 );
    } 
    

    【讨论】:

    • 我将 (null) 设为“Last-Modified”。 NSLog(@"%@", [((NSHTTPURLResponse *)response) allHeaderFields]) 表明该字典中没有“Last-Modified”键。不同之处在于我正在设置同步请求。
    • 你在哪里保存字符串savedmod这个策略?我使用上述方法获得了当前的 etag,但我想像您在原始问题中所做的那样进行比较。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-06
    • 1970-01-01
    • 1970-01-01
    • 2019-02-26
    相关资源
    最近更新 更多