我做了更多调查,并能够为 android 和 ios 编写一个 cordova 插件,以从 WL 生成的预期属性文件中读取值。以下是不同的来源。有关编写 cordova 插件的更多信息,请参阅WorkLight 入门第 6 节。这实际上相当容易。一旦你了解了 Objective-C 的不同之处,只需几分钟。
安卓代码
WorklightPropertiesPlugin.java
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;
import android.content.res.AssetManager;
import android.content.res.Resources;
public class WorklightPropertiesPlugin extends CordovaPlugin {
@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
boolean handled = false;
String responseText = "";
if(action.equalsIgnoreCase("serverURL")) {
try {
AssetManager am = this.cordova.getActivity().getApplicationContext().getAssets();
InputStream is = am.open("wlclient.properties");
Properties prop = new Properties();
prop.load(is);
String wlServerProtocol = prop.getProperty("wlServerProtocol");
String wlServerHost = prop.getProperty("wlServerHost");
String wlServerPort = prop.getProperty("wlServerPort");
String wlServerContext = prop.getProperty("wlServerContext");
responseText = wlServerProtocol + "://" + wlServerHost + ":" + wlServerPort + wlServerContext;
handled = true;
} catch(IOException e) {
callbackContext.error("Error loading properties " + e.getLocalizedMessage());
}
}
if(handled) {
callbackContext.success(responseText);
}
return handled;
}
}
iOS 代码
WorklightPropertiesPlugin.h
#import <Foundation/Foundation.h>
#import <Cordova/CDV.h>
@interface WorklightPropertiesPlugin : CDVPlugin
- (void) serverURL:(CDVInvokedUrlCommand*) command;
@end
WorklightPropertiesPlugin.m
#import "WorklightPropertiesPlugin.h"
@implementation WorklightPropertiesPlugin
- (void) serverURL:(CDVInvokedUrlCommand*)command{
NSString * response = nil;
CDVPluginResult *pluginResult = nil;
NSString* plistLoc =[[NSBundle mainBundle]pathForResource:@"worklight" ofType:@"plist"];
if(plistLoc == nil){
[NSException raise:@"[Remote Load Initialization Error]" format:@"Unable to locate worklight.plist"];
}
NSDictionary* wlProps = [NSDictionary dictionaryWithContentsOfFile:plistLoc];
NSString* proto = [wlProps valueForKey:@"protocol"];
NSString* host = [wlProps valueForKey:@"host"];
NSString* port = [wlProps valueForKey:@"port"];
NSString* wlServerContext = [wlProps valueForKey:@"wlServerContext"];
if(proto == nil || host == nil || port == nil){
[NSException raise:@"[Remote Load Initialization Error]" format:@"host, port and protocol are all required keys in worklight.plist"];
}
response = [NSString stringWithFormat:@"%@://%@:%@%@", proto, host, port, wlServerContext];
pluginResult = [CDVPluginResult resultWithStatus: CDVCommandStatus_OK messageAsString:response];
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
@end