首頁我們要創(chuàng)建一個 Cordova 項目珠叔,并導入到 Xcode 中。
假設我們需要創(chuàng)建一個 TestPlugin 插件穿铆,包含一個 test 方法热芹。在 Plugins 文件夾下創(chuàng)建 estPlugin.h 和 TestPlugin.m 文件,并輸入下面的代碼:
/********* TestPlugin.h Cordova Plugin Header *******/
@interface TestPlugin : CDVPlugin
- (void)test:(CDVInvokedUrlCommand *)command;
@end
/***************** TestPlugin.m ********************/
#import "TestPlugin.h"
@implementation TestPlugin
- (void)test:(CDVInvokedUrlCommand *)command
{
UIAlertView ?*alertview = [[UIAlertView alloc] initWithTitle:@"標題"message:@"Hello world!" delegate:self ?cancelButtonTitle:@"取消" otherButtonTitles:@"確定", nil];
[alertview show];
}
@end
提示一下對Objective C語言不熟悉的朋友胎撤,類文件都是拆分為h和m兩部分晓殊,h包含了對類和方法的定義,m包含了具體實現(xiàn)哩照。而我們常用的Java和PHP是將類的定義和實現(xiàn)放在一個文件中挺物。上面的插件我們只提供一個test方法,它的功能是顯示一個原生的提示框飘弧。
下面识藤,我們需要將插件的信息寫入配置文件,Cordova才能找到插件次伶。打開Staging文件夾下的config.xml文件痴昧,在widget標簽下輸入:
這樣就完成了JavaScript和Objective C的橋接,大功告成冠王,我們可以使用JavaScript來調用TestPlugin插件了赶撰。
cordova.exec(null,null,"TestPlugin","test",[]);
上面的代碼調用了插件的test方法,如果一切操作正確的話柱彻,你將看到一個類似于confirm的提示框豪娜。
一個最簡單的Cordova插件就開發(fā)完成了.