Cordova学习--iOS自定义插件
上一篇文章中我們已經(jīng)成功創(chuàng)建了一個(gè)App,在這一篇中,我們實(shí)現(xiàn)自定義原生插件,由js調(diào)用原生插件。在這里我們實(shí)現(xiàn)功能如下
一、創(chuàng)建插件文件 在plugins文件夾下創(chuàng)建插件EchoPlugin,繼承自CDVPlugin,文件創(chuàng)建完成以后會(huì)報(bào)找不到頭文件的錯(cuò)誤,把#import <Cordova/Cordova.h>替換成#import <Cordova/CDVPlugin.h>即可
二、聲明方法實(shí)現(xiàn)插件代碼
在EchoPlugin.h文件中聲明一個(gè)方法,作為原生插件對(duì)外暴露的接口供js代碼調(diào)用,在.m文件中實(shí)現(xiàn)該方法實(shí)現(xiàn)iOS原生功能。
主要實(shí)現(xiàn)代碼如下:
- (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]; } 復(fù)制代碼三、配置插件
注意:
要配置App最外層的config.xml文件,最外層的是全局文件,修改并編譯之后會(huì)在staging下的配置文件中同樣寫(xiě)入配置代碼。如果單獨(dú)修改staging文件夾下的config.xml文件,編譯之后會(huì)被最全局的config.xml覆蓋恢復(fù)原樣。
index.html頁(yè)面是Cordova創(chuàng)建的應(yīng)用程序的入口,我們可以修改這個(gè)頁(yè)面調(diào)用iOS原生功能。從js映射到插件類(lèi)通過(guò)exec函數(shù)實(shí)現(xiàn)
exec(<successFunction>, <failFunction>, <service>, <action>, [<args>]); 復(fù)制代碼說(shuō)明:
successFunction:成功的回調(diào)函數(shù)
failFunction:失敗的回調(diào)函數(shù)
service:調(diào)用原生代碼的服務(wù)名,和config.xml文件中的feature的name值保持一致
action:要調(diào)用的插件方法
args:要調(diào)用方法的參數(shù),是一個(gè)數(shù)組
修改index.html頁(yè)面如下:
<!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傳的參數(shù)!"]);}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> 復(fù)制代碼注意: 修改index.html頁(yè)面也要修改最外層的全局頁(yè)面
到此,第二篇文章結(jié)束。
總結(jié)
以上是生活随笔為你收集整理的Cordova学习--iOS自定义插件的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Zookeeper 3.5启动时 808
- 下一篇: 3.1集合相关知识点