IOS下Phonegap 插件开发

14 篇文章 0 订阅
用上一节我们创建的Hello 项目来示例

http://www.mwebgl.com/dede/a/kaifakuangjia/Phonegapjishuwendang/2012/0511/125.html

Hello项目中创建 js   HelloPlugin.js

var HelloPlugin = { callNativeFunction: function (success, fail, resultType) {
return Cordova.exec(
success, fail, "com.tricedesigns.HelloPlugin",
"nativeFunction", [resultType]);

}

};

创建
Native 类

右击plugins文件新建文件


Figure 1. Creating the new file.  


在新建的文件中选择
Objective-C class 

Figure 2. Selecting the Object-C class template.


命名  HelloPlugin    并且创建

Figure 3. Naming the class.

点击下一步

在你的项目中新建了一个.h的文件 实现 .m文件的接口


Figure 4. The new native class files.

在你的.h文件中写入一下代码,此代码为接口代码

#import <Cordova/CDV.h>
@interface HelloPlugin : CDVPlugin

- (void) nativeFunction:(NSMutableArray*)
arguments withDict:(NSMutableDictionary*)options;

@end


在你的.m文件中写入实现.h接口

#import "HelloPlugin.h"

@implementation HelloPlugin

- (void) nativeFunction:(NSMutableArray*)
arguments withDict:(NSMutableDictionary*)options {

//get the callback id NSString *callbackId = [arguments pop];

NSLog(@"Hello, this is a native function called from PhoneGap/Cordova!");

NSString *resultType = [arguments objectAtIndex:0]; CDVPluginResult *result;

if ( [resultType isEqualToString:@"success"] ) {

result = [CDVPluginResult resultWithStatus:
CDVCommandStatus_OK messageAsString: @"Success :)"];

[self writeJavascript:[result toSuccessCallbackString:callbackId]];

} else {

result = [CDVPluginResult resultWithStatus:
CDVCommandStatus_ERROR messageAsString: @"Error :("];

[self writeJavascript:[result toErrorCallbackString:callbackId]]; } }

@end



在index.html中调用 
<script type="text/javascript" charset="utf-8" src="HelloPlugin.js"></script>

调用一下函数


function callNativePlugin( returnSuccess ) {

HelloPlugin.callNativeFunction(

nativePluginResultHandler, nativePluginErrorHandler, returnSuccess );

}

function nativePluginResultHandler (result) {

alert("SUCCESS: \r\n"+result );

}

function nativePluginErrorHandler (error) {

alert("ERROR: \r\n"+error );

}

写入标记调用

<body οnlοad="onBodyLoad()">

<h1>Hey, it's Cordova!</h1>
<button οnclick="callNativePlugin('success');">SUCCESS!</button>
<button οnclick="callNativePlugin('error');">ERROR!</button>

</body>



在项目中打开  Cordova.plist.文件写入关联文件
 key  com.tricedesigns.HelloPlugin  和  value  "HelloPlugin"

Figure 5. Editing Cordova.plist.

保存你的更改并且运行项目


Figure 6. The application running in the iOS simulator.

运行成功!

查看xcode的打印日志


Figure 7. Logged information in the Xcode debug console.




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值