使用Cordova開發(fā)iOS App -- 開發(fā)iOS插件

本篇在上一篇--Cordova的環(huán)境搭建基礎(chǔ)上以一個(gè)例子講解如何為Cordova開發(fā)iOS插件。

一、創(chuàng)建插件文件

在Plugins文件夾下創(chuàng)建插件文件夾命名為com.catchzeng.testplugin

Plugins

創(chuàng)建類TestPlugin繼承于CDVPlugin
TestPlugin

注意:創(chuàng)建類后會(huì)報(bào)頭文件#import <Cordova/Cordova.h>找不到的問題,替換成#import <Cordova/CDVPlugin.h>即可。

二、實(shí)現(xiàn)插件代碼

該插件實(shí)現(xiàn)的功能是JS調(diào)用原生的代碼彈出一個(gè)自定義視圖控制器(附帶參數(shù)),并在彈起后回傳參數(shù)給JS。


Plugin

@implementation TestPlugin

-(void)testWithTitle:(CDVInvokedUrlCommand *)command{
    if (command.arguments.count>0) {
        //customize argument
        NSString* title = command.arguments[0];
        
        TestViewController* testViewCtrl = [[TestViewController alloc]init];
        [self.viewController presentViewController:testViewCtrl animated:YES completion:^{
            CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"我是OC回傳的參數(shù)!"];
            testViewCtrl.labTitle.text = title;
            [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        }];
    }else{
        //callback
        CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"沒有參數(shù)"];
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }
}

@end

說明:
command.arguments:JS傳遞過來的參數(shù)列表,可自行協(xié)定參數(shù)的格式
CDVPluginResult:插件結(jié)果回調(diào)類,用于描述結(jié)果的狀態(tài)和回傳數(shù)據(jù)給JS
command.callbackId:對(duì)應(yīng)回調(diào)JS時(shí),指定發(fā)送的函數(shù)id

三、測(cè)試插件

在config.xml文件中加入以下代碼讓JS能夠調(diào)用我們的OC類,需要注意的是需要配置Staging下的config.xml,而不是外部的

<feature name="ocTestPlugin">
  <param name="ios-package" value="TestPlugin" />
</feature>

修改index.html

<!DOCTYPE html>
<html>
    <head>
        <title>testPlugin</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 testPlugin() {
                cordova.exec(testSuccess,testFailed,"ocTestPlugin","testWithTitle",["我是JS傳的參數(shù)!"]);
            }
            function testSuccess(msg) {
                alert(msg);
            }
            function testFailed(msg) {
                alert('failed: ' + msg);
            }
            </script>
            </head>
    
    <body style="padding-top:100px">
        <button style="font-size:17px;" onclick="testPlugin();">測(cè)試iOS插件</button>
        <br>
    </body>
</html>

最后附上工程的結(jié)構(gòu)圖

Project

開發(fā)iOS插件部分就先講到這里,下一篇將講解如何將本篇的插件打包供前端人員使用。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容