Cordova学习--iOS自定义插件
上一篇文章中我們已經成功創建了一個App,在這一篇中,我們實現自定義原生插件,由js調用原生插件。在這里我們實現功能如下
一、創建插件文件 在plugins文件夾下創建插件EchoPlugin,繼承自CDVPlugin,文件創建完成以后會報找不到頭文件的錯誤,把#import <Cordova/Cordova.h>替換成#import <Cordova/CDVPlugin.h>即可
二、聲明方法實現插件代碼
在EchoPlugin.h文件中聲明一個方法,作為原生插件對外暴露的接口供js代碼調用,在.m文件中實現該方法實現iOS原生功能。
主要實現代碼如下:
- (void)echo:(CDVInvokedUrlCommand*)command {CDVPluginResult *pluginResult = nil;NSString *echo = [command.arguments objectAtIndex:0];if (echo!=nil&&[echo length]>0) {FirstViewController *testVC = [[FirstViewController alloc] init];UINavigationController *navVC = [[UINavigationController alloc] initWithRootViewController:testVC];[self.viewController presentViewController:navVC animated:YES completion:^{CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:echo];[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];}];pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:echo];}else{pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];}[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId]; } 復制代碼三、配置插件
注意:
要配置App最外層的config.xml文件,最外層的是全局文件,修改并編譯之后會在staging下的配置文件中同樣寫入配置代碼。如果單獨修改staging文件夾下的config.xml文件,編譯之后會被最全局的config.xml覆蓋恢復原樣。
index.html頁面是Cordova創建的應用程序的入口,我們可以修改這個頁面調用iOS原生功能。從js映射到插件類通過exec函數實現
exec(<successFunction>, <failFunction>, <service>, <action>, [<args>]); 復制代碼說明:
successFunction:成功的回調函數
failFunction:失敗的回調函數
service:調用原生代碼的服務名,和config.xml文件中的feature的name值保持一致
action:要調用的插件方法
args:要調用方法的參數,是一個數組
修改index.html頁面如下:
<!DOCTYPE html> <html><head><title>EchoPlugin</title><meta http-equiv="Content-type" content="text/html; charset=utf-8"><script type="text/javascript" charset="utf-8" src="cordova.js"></script><script type="text/javascript" charset="utf-8">function EchoPlugin() {cordova.exec(testSuccess,testFailed,"EchoPlugin","echo",["我是JS傳的參數!"]);}function testSuccess(msg) {alert(msg);}function testFailed(msg) {alert('failed: ' + msg);}</script></head><body style="padding-top:50px"><button style="font-size:17px;" onclick="EchoPlugin();">Use iOS Plugin</button> <br></body> </html> 復制代碼注意: 修改index.html頁面也要修改最外層的全局頁面
到此,第二篇文章結束。
總結
以上是生活随笔為你收集整理的Cordova学习--iOS自定义插件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Zookeeper 3.5启动时 808
- 下一篇: 3.1集合相关知识点