iosswiftxcodeplistinfo-plist

How to get a value from InfoPlist.string at runtime?


In Project/SupportingFiles/en.lproj/InfoPlist.strings I have this value:

NSUserTrackingUsageDescription = "dummy";

It's a localized InfoPlist.strings file, it can be in various languages. In this case, the folder en.lproj is for English.

For example, imagine that before compiling I can writte to NSUserTrackingUsageDescription a value, and I need to ensure if it's "dummy" at runtime.

It is possible to check in Swift if NSUserTrackingUsageDescription is "dummy" or another string at runtime with Swift?

I'm doing a research but I can't find any Swift code to check that.

Edit

I tried with this code:

let string = Bundle.main.infoDictionary!["NSUserTrackingUsageDescription"] as! String
    
if (string == "dummy"){
     logger.debug("NSUserTrackingUsageDescription is dummy")
}else{
     logger.debug("NSUserTrackingUsageDescription is \(string)")
}

But it's not working because it enters the else and prints this:

LauncherViewController.requestAppTrackingTransparencyPermission():131

  • NSUserTrackingUsageDescription is dummy, replaced with translation from InfoPlist.strings

I don't know why the system is adding , replaced with translation from InfoPlist.strings to dummy.


Solution

  • Best approach is to use:

    guard let string = Bundle.main.object(forInfoDictionaryKey: "NSUserTrackingUsageDescription") as? String 
        else { fatalError("not found") }
    

    Note from Apple's docs:

    Use of this method is preferred over other access methods because it returns the localized value of a key when one is available.