xcode 检索文件创建或修改日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13497500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 02:09:15  来源:igfitidea点击:

Retrieve file creation or modification date

iosobjective-cxcodelast-modifiednsdocumentdirectory

提问by Robert

I'm using this piece of code to try to retrieve the last modified date of a file:

我正在使用这段代码来尝试检索文件的最后修改日期:

NSError *error = nil;
NSDictionary *attributes = [[NSFileManager defaultManager] attributesOfItemAtPath: myFilePath error:&error];

        if (attributes != nil) {
            NSDate *date = (NSDate*)[attributes objectForKey: NSFileModificationDate];
            NSLog(@"Date modiifed: %@", [date description]);
        }
        else {
            NSLog(@"Not found");
        }

This works well for files in the main bundle but not if the file is located in a subdirectory of the app's document folder, with myFilePathlike this:

这适用于主包中的文件,但如果文件位于应用程序文档文件夹的子目录中,则不适用,myFilePath如下所示:

/Users/User/Library/Application Support/iPhone Simulator/6.0/Applications/The App ID Number/Documents/mySubdirectory/My Saved File

It keeps returning "not found".

它不断返回“未找到”。

I know the file is there, as I can view it with finder. I also tried removing the spaces in the file name but this had no effect.

我知道文件在那里,因为我可以用finder查看它。我也尝试删除文件名中的空格,但这没有效果。

The error log says no such file or directory, so it looks like something must've gone wrong when I tried to copy the file to the document directory.

错误日志说没有这样的文件或目录,所以当我试图将文件复制到文档目录时,它看起来一定出了问题。

Weird thing is, iterating through the document sub directory with contentsOfDirectoryAtPathshows the file as being present.

奇怪的是,遍历文档子目录并contentsOfDirectoryAtPath显示文件存在。

I've tried hard-coding the path and retrieving it programmatically, with:

我尝试硬编码路径并以编程方式检索它,使用:

*myFolder = [documentsDirectory stringByAppendingPathComponent:@"myFolder"];
*myFilePath = [myFolder stringByAppendingPathComponent:theFileName];

Can anyone see where I'm going wrong?

谁能看到我哪里出错了?

回答by zvjerka24

Try this. I had same problem and solved with something like next:

尝试这个。我有同样的问题,并解决了类似的问题:

NSURL *fileUrl = [NSURL fileURLWithPath:myFilePath];
NSDate *fileDate;
[fileUrl getResourceValue:&fileDate forKey:NSURLContentModificationDateKey error:&error];
if (!error)
{
//here you should be able to read valid date from fileDate variable
}

hope it helped ;)

希望它有所帮助;)

回答by coldfire

Swift 3 solution:

斯威夫特 3 解决方案:

func fileModificationDate(url: URL) -> Date? {
    do {
        let attr = try FileManager.default.attributesOfItem(atPath: url.path)
        return attr[FileAttributeKey.modificationDate] as? Date
    } catch {
        return nil
    }
}

回答by FBente

Here is a Swift like solution of @zvjerka24 answer:

这是@zvjerka24 答案的类似 Swift 的解决方案:

func lastModified(path: String) -> NSDate? {
    let fileUrl = NSURL(fileURLWithPath: path)
    var modified: AnyObject?
    do {
        try fileUrl.getResourceValue(&modified, forKey: NSURLContentModificationDateKey)
        return modified as? NSDate
    } catch let error as NSError {
        print("\(#function) Error: \(error)")
        return nil
    }
}

回答by Tonnie

If you get the error:

如果您收到错误:

"CFURLCopyResourcePropertyForKey failed because it was passed this URL which has no scheme"

“CFURLCopyResourcePropertyForKey 失败,因为它传递了这个没有方案的 URL”

You can try to solve this by appending "file:///" to your NSString file path before converting it to NSURL, it worked in my case.

您可以尝试通过在将“file:///”转换为 NSURL 之前将“file:///”附加到您的 NSString 文件路径来解决此问题,它在我的情况下有效。

回答by Alexandre G

Can also do:

还可以这样做:

NSURL* file = ...
NSError* error;`
NSDate *creationDate = [[NSFileManager defaultManager] attributesOfItemAtPath:file.path error:&error].fileCreationDate;

回答by Shikha Budhiraja

For any file in macOS system we can easily get modification date by using any of below mentioned options:

对于 macOS 系统中的任何文件,我们可以使用以下任何选项轻松获取修改日期:

Way 1:

方式一:

  • NSString *path = @"path to file";
  • NSError *err = nil;
  • NSDictionary *dic2 = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:&err];
  • NSLog(@"File modification Date:%@", dic2[NSFileModificationDate]);
  • NSString *path = @"文件路径";
  • NSError *err = nil;
  • NSDictionary *dic2 = [[NSFileManager defaultManager] attributesOfItemAtPath:path error:&err];
  • NSLog(@"文件修改日期:%@", dic2[NSFileModificationDate]);

Way 2:

方式二:

  • MDItemRef itemRef = MDItemCreate(kCFAllocatorDefault, (__bridge CFStringRef)path);
  • NSArray *attributeNames = (__bridge NSArray *)MDItemCopyAttributeNames(itemRef);
  • NSDictionary *attributes = (__bridge NSDictionary *) MDItemCopyAttributes(itemRef, (__bridge CFArrayRef) attributeNames);

  • CFDateRef modifDate = MDItemCopyAttribute(itemRef, kMDItemContentModificationDate);

  • NSDate* modificationDate = (__bridge NSDate*) modifDate;
  • NSLog(@"Modification Date%@", modificationDate);
  • MDItemRef itemRef = MDItemCreate(kCFAllocatorDefault, (__bridge CFStringRef)path);
  • NSArray *attributeNames = (__bridge NSArray *)MDItemCopyAttributeNames(itemRef);
  • NSDictionary *attributes = (__bridge NSDictionary *) MDItemCopyAttributes(itemRef, (__bridge CFArrayRef) attributeNames);

  • CFDateRef modifDate = MDItemCopyAttribute(itemRef, kMDItemContentModificationDate);

  • NSDate* modifyDate = (__bridge NSDate*) modifDate;
  • NSLog(@"修改日期%@", modifyDate);

You can also print various other attributes provided by MDItem : NSLog(@"All attributes%@", attributes);

您还可以打印 MDItem 提供的各种其他属性: NSLog(@"All attributes%@", attributes);