Home > database >  Cordova plugin variables
Cordova plugin variables

Time:12-17

How can I use variables in the Swift/Kotlin code of my Cordova plugin, for iOS and Android?

I mean the variables that were defined in config.xml, and now live in package.json, that looked like this:

<plugin name="cordova-plugin-device" spec="^1.1.0">
    <variable name="MY_VARIABLE" value="my_variable_value" />
</plugin>

... I know how to set these when installing my custom plugin, but I don't see any mention in the documentation about how to access them within the plugin.

CodePudding user response:

Variables are not accesible from code, variables are just a way of changing a value in the plugin.xml, can be used to make a SDK version configurable, or to write the value to the Info.plist or AndroidManifest.xml or strings.xml or other native files, then you can read those files from the native code as you would do on iOS/Android.

In example to read from Info.plist you would do it like this:

NSString *myValue = [NSString stringWithFormat:@"%@", [[NSBundle mainBundle] objectForInfoDictionaryKey:@"MyValue"]];

To write in the Info.plist

<config-file target="*-Info.plist" parent="MyValue">
   <string>$MY_VARIABLE</string>
</config-file>

To read from strings.xml

Activity activity = cordova.getActivity();
    String packageName = activity.getPackageName();
    int resId = activity.getResources().getIdentifier(“MyValue”, "string", packageName);
String myValue = activity.getString(resId);

To write to strings.xml

<config-file target="./res/values/strings.xml" parent="/resources">
    <string name="MyValue">$MY_VARIABLE</string>
</config-file>
  • Related