Get build date and time in Swift
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?
Ответы (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
Вопросы из категории :
- swift Как я могу программным образом определить, работает ли мое приложение в симуляторе iphone?
- swift iOS: Convert UTC NSDate to local Timezone
- swift Как установить цель и действие для UIBarButtonItem во время выполнения
- swift Жирный и не жирный текст в одном UILabel?
- swift Найти касательную точки на кубической кривой безье
- swift Как я могу рассчитать разницу между двумя датами?
- swift How to get text / String from nth line of UILabel?
- swift Можно ли программно прокрутить до нужной строки в UIPickerView?
- swift Отключение клавиатуры в UIScrollView
- swift Как контролировать межстрочный интервал в UILabel
- build-time Get build date and time in Swift
- build-time Есть ли способ определить константу во время сборки в Go?
- build-time Почему Visual Studio сообщает, что в моем решении / на сайте 0 ошибок и что в нем есть ошибки (а затем браузер выдает «Ошибка 404.17»)?
- build-time Ошибка компоновщика Apple Mach-O в проекте с Coredata при создании класса NSManagedObject
- build-time Почему Android Studio очищается перед сборкой?
- build-time Как эффективно восстановить проект go при использовании Docker Compose?
- build-time Почему бы не добавить mavenLocal () во все приложения Android?
- build-time Build time: Visual Studio 2015-2017 build very slow
- build-time OutOfMemoryError: превышен лимит накладных расходов GC после обновления плагина gradle в Android Studio 3.0
- build-time Как заставить мое приложение запускаться на другом языке?