首页 > 解决方案 > 为什么 FileManager.default.attributesOfItem 在 NSFileCreationDate 中返回当前日期?

问题描述

尽管我已经检查了有关如何获取创建日期的其他答案,但这对我来说似乎并不奏效。

这就是我提取创建日期的方式。

class func extractFileCreatedDate(filepath: String) -> String{

    var dateString = ""
    do{

        let aFileAttributes = try FileManager.default.attributesOfItem(atPath: filepath) as [FileAttributeKey:Any]
        let theCreationDate = aFileAttributes[FileAttributeKey.creationDate] as? Date ?? Date()

        let formatter: DateFormatter = DateFormatter()
        formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX") as Locale?
        formatter.timeZone = TimeZone.init(abbreviation: "GMT")
        formatter.dateFormat = "MM/dd/yyyy HH:mm:ss"

        //MARK:- Share App Submit Date
        if let readDate:String = formatter.string(from: theCreationDate){
            dateString = readDate
        }

    } catch let theError as Error{
        print("file not found \(theError)")
    }

    return dateString
}

所以我通过打印得到的响应是:

在此处输入图像描述

如果我在本地存储中检查此文件,则创建日期不同:

在此处输入图像描述

在调试中,我也得到当前日期而不是创建日期:

在此处输入图像描述 在此处输入图像描述

如果我做错了什么,请建议我。我期待的是它应该返回相同的创建日期。或者也许我错过了一些东西,请帮帮我。

谢谢!

标签: iosswiftnsfilemanager

解决方案


creationDate 将始终从我们的应用程序返回文件的创建日期,而不是物理存储(Mac)的创建日期。

为了测试这个:

1:将文件添加到您的包(在过去的日期创建)并测试您的代码,它将返回您当前的日期(与您现在得到的相同)。

2:删除应用程序将iPhone的日期手动更改为过去For Ex的任何日期。01-01-2019运行 App,可以看到创建日期为01-01-2019

3:再次将日期更改为今天的日期并测试,可以看到结果仍然是01-01-2019,因为创建日期是过去的日期

希望对你有帮助!!!


推荐阅读