Learn Courses My Dashboard

How to set a variable to the build date

Is there a way to capture the date an app was built in Xcode into a variable?

I haven’t heard of this, but it would be something that could possibly be captured multiple times a day right?

I found this on stackoverflow.

var buildDate:NSDate
 {
     if let infoPath = Bundle.main.path(forResource: "Assets.xcassets", ofType: nil),
        let infoAttr = try? FileManager.default.attributesOfItem(atPath: infoPath),
        let infoDate = infoAttr[FileAttributeKey(rawValue: "NSFileCreationDate")] as? NSDate
     { return infoDate }
     return NSDate()
 }

var compileDate:Date
{
    let bundleName = Bundle.main.infoDictionary!["CFBundleName"] as? String ?? "Info.plist"
    if let infoPath = Bundle.main.path(forResource: bundleName, ofType: nil),
       let infoAttr = try? FileManager.default.attributesOfItem(atPath: infoPath),
       let infoDate = infoAttr[FileAttributeKey.creationDate] as? Date
    { return infoDate }
    return Date()
}

In both cases they retrieve the date right now but as GMT so add or subtract your timezone to get the local date.

In the first one you can substitute whatever filename you like such as “Info.plist” and the result is the same.

Place the code somewhere as a global and then use an .onAppear { } to print the output to the Console… or do whatever you want with it.

.onAppear {
    print("Build Date: \(buildDate)")
    print("Compile Date: \(compileDate)")
}
1 Like

Right.

Looks like it worked. I’ll see tomorrow whether it returned the compile date or the current date.

I didn’t have to put it in an onAppear. I just put it inside a Text.

Worked like a charm. Can you explain why that works? It looks like it’s returning the creation date of the file, but why would that change when the app is compiled?

It could be pulling that date out of the Build Folder so that might be the reason. I’m guessing that when the App is installed on a device the date will always be the date of installation as opposed to when you began coding it.

I don’t know the nitty gritty stuff that goes on behind the scenes with the source code files and the build folder so it’s all a bit of black magic.

Well, once again, you came up with the solution. Thanks.

1 Like