Get Swift SDK version in code with Realm 4


(jay) #1

Is there a way to get the Swift SDK version in code with Realm 4?

We used to be able to do this

    if let sdkVersion = Bundle(for: Realm.self).infoDictionary?["CFBundleShortVersionString"] {
        print("Realm version: \(sdkVersion)")
    }

But with Realm 4, it’s thowing an error

Cannot convert value of type ‘Realm.Type’ to expected argument type ‘AnyClass’ (aka ‘AnyObject.Type’)


(jay) #2

Not sure what the deal is with not being able to use Realm.self any longer but this super hacky code will get the realm version from the info.plist added to the project via a podFile. This ONLY works for Swift projects where Realm was added with pod install or cocoapods AND Sandboxing is off or has been removed (XCode 11+ go to Targets->Project Name->Signing & Capabilities and remove sandboxing by clicking the X on the right)

I really don’t understand why there can’t be a simple property

print(Realm.version)

to get the currently installed version of the sdk but alas, that request has gone unanswered for years.

let pathOfThisFile = #file
var path = URL(fileURLWithPath: pathOfThisFile)
path.deleteLastPathComponent() //remove the enclosing folder name
path.deleteLastPathComponent() //and then remove the next up folder, leaving the project folder
let podPath = path.appendingPathComponent("Pods")
let finalPathUrl = podPath.appendingPathComponent("Target Support Files/Realm/")

if let realmBundle = Bundle(url: finalPathUrl) {
    if let infoFileDict = realmBundle.infoDictionary {
        if let sdkVersion = infoFileDict["CFBundleShortVersionString"] {
            print("Realm version: \(sdkVersion)")
        } else {
            print("realm CFBundleShortVersionString key not found in info.plist")
        }
    } else {
        print("infoDictionary not found")
    }

} else {
    print("path to info.plist not found")
}