简体   繁体   中英

How to access host app version from framework in iOS?

I have one host app MyApp and one linked framework MyFramework in same workspace for a large iOS project. Let's say MyFramework requires to know MyApp release version (or current build number) for some reasons. How can I deal with this situation? Can a framework access host apps .plist in anyway? or is there any better design?

Answer:

Accessing content of Info.plist is possible if you can create proper Bundle OR NSBundle object of the host application. Then you can access infoDictionary property to access full content.

Now the main question is how to create the Bundle object of host application? There are four initialisers of Bundle . I prefer to use init?(identifier:) since others takes class name or path from MyApp as parameter, these info might not be available from your MyFramework

在此处输入图片说明

So to access MyApp 's Info.plist use the following code.

if let hostInfoDic = Bundle(identifier: "com.company.MyApp")?.infoDictionary {
      print("CFBundleShortVersionString: \(hostInfoDic["CFBundleShortVersionString"])")
      print("CFBundleVersion: \(hostInfoDic["CFBundleVersion"])")
} else {
  // Log error
  // ... Fallback handler 
}

In your framework's configuration call, you can ask for host app's bundle identifier as an additional parameter.

Note:

You can not directly use Bundle.main.infoDictionary , since this will give you bundle info from the current executable directory which might be your framework.

From Apple Documentation

Discussion

The main bundle lets you access the resources in the same directory as the currently running executable. For a running app, the main bundle offers access to the app's bundle directory. For code running in a framework, the main bundle offers access to the framework's bundle directory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM