Get build date and time in Swift

swift build-time

4387 просмотра

2 ответа

I'm using __DATE__ and __TIME__ in Objective-C to get the build date and time of my app. I can't find a way to get this information in Swift. Is it possible?

Автор: David Potter Источник Размещён: 12.11.2019 09:51

Ответы (2)

9 плюса


You can use #line, #column, and #function.

Original answer:

Create a new Objective-C file in your project, and when Xcode asks, say yes to creating the bridging header.

In this new Objective-C file, add the following the the .h file:

NSString *compileDate();
NSString *compileTime();

And in the .m implement these functions:

NSString *compileDate() {
    return [NSString stringWithUTF8String:__DATE__];

NSString *compileTime() {
    return [NSString stringWithUTF8String:__TIME__];

Now go to the bridging header and import the .h we created.

Now back to any of your Swift files:

println(compileDate() + ", " + compileTime())
Автор: nhgrif Размещён: 08.11.2014 02:13

24 плюса

You can get the build date and time without reverting to objective-C. When the app is built, the Info.plist file placed in the bundle is always created from the one in your project. So the creation date of that file matches the build date and time. You can always read files in your app's bundle and get their attributes. So you can get the build date in Swift by accessing its Info.plist file attributes:

 var buildDate:NSDate 
     if let infoPath = NSBundle.mainBundle().pathForResource("Info.plist", ofType: nil),
        let infoAttr = try? NSFileManager.defaultManager().attributesOfItemAtPath(infoPath),
        let infoDate = infoAttr["NSFileCreationDate"] as? NSDate
     { return infoDate }
     return NSDate()

Note: this is the post that got me to use the bridging header when I initially had this problem. I found this "Swiftier" solution since then so I thought I'd share it for future reference.

[EDIT] added compileDate variable to get the latest compilation date even when not doing a full build. This only has meaning during development since you're going to have to do a full build to release the application on the app store but it may still be of some use. It works the same way but uses the bundled file that contains the actual code instead of the Info.plist file.

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()
Автор: Alain T. Размещён: 17.07.2016 12:58
Вопросы из категории :