在开发App的过程中,某一模块需要用HTML5/JavaScript实现,也就是在Native工程中嵌入HTML/JavaScript模块,该怎么办呢?
一、ionic安装及工程创建
1、下载并安装node.js
2、使用node.js 包管理工具npm安装cordova ionic
$ npm install -g cordova ionic
3、创建ionic项目
$ ionic start html5App tabs
4、添加平台 (主要是ios、android)
$ cd html5App
$ ionic platform add ios
$ ionic build ios
$ ionic emulate
注:emulate是运行ios模拟器,一般真机调试效果更好。
5、打开生成的ios工程
$ cd platforms
$ cd ios
二、ionic工程嵌入到iOS Native App中
1、Xcode创建一个工程IonicDemo,将HTML5 App工程文件Copy到IonicDemo文件
Copy:
To:
2、添加Copy的HTML5文件到IonicDemo工程文件中,我觉得在IonicDemo中”New Group“并把文件添加进去,这样便于维护。
AlarmViewController是直接在工程中添加的ViewController新文件,只需要在头文件中添加如下代码即可:
#import "CDVViewController.h"
@interface AlarmViewController : CDVViewController
@end
然后,像使用平常的ViewController一样随意使用就可以了。
解决办法:添加如下framework即可,当然也要添加libCordova.a
三、Cordova插件配置及代码编写(用于Native与JavaScript通信)
1、在工程目录下创建插件DeviceDeInfoPlugin、DeviceAlarmInfoPlugin
以DeviceInfoPlugin为例:DeviceInfoPlugin继承于Cordova基类CDVPlugin
</pre><pre class="objc" name="code">#import "CDVPlugin.h"
@interface DeviceInfoPlugin : CDVPlugin
- (void)deviceInfoPlugin:(CDVInvokedUrlCommand*)command;
@end
- (void)deviceInfoPlugin:(CDVInvokedUrlCommand*)command
{
CDVPluginResult* pluginResult = nil;
NSString* firstArg = [command.arguments objectAtIndex:0];
NSLog(@"--->Javascript, I got the information:%@", firstArg);
NSString sendString = @"Hello, JavaScrip";
if (firstArg != nil) {
pluginResult = [CDVPluginResult
resultWithStatus:CDVCommandStatus_OK
messageAsString:sendString];
}else{
pluginResult = [CDVPluginResult
resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Arg
was null."];
}
[self.commandDelegate sendPluginResult:pluginResult
callbackId:command.callbackId];
}
2、配置config.xml文件,在<widget>...</widget>中加入插件
<feature name="DeviceInfoPluginName">
<param name="ios-package" value="DeviceInfoPlugin" />
<param name="onload" value="true" />
</feature>
<feature name="DeviceAlarmInfoPluginName">
<param name="ios-package" value="DeviceAlarmInfoPlugin" />
<param name="onload" value="true" />
</feature>
注:DeviceInfoPluginName、DeviceAlarmInfoPluginName是数据交互的关键
3、在www目录下的*.html文件中回调插件方法
function buttonClick(){
Cordova.exec(callBackDeviceInfoPlugin, failFunction,
"DeviceInfoPluginName", "deviceInfoPlugin", ["I need device
info."]);
Cordova.exec(callBackDeviceAlarmInfoPlugin, failFunction,
"DeviceAlarmInfoPluginName", "deviceAlarmInfoPlugin", ["I need
alarm info."]);
}