在上一篇--開發(fā)iOS插件中我們開發(fā)了一個插件,本篇將講解如何將插件打包。
一、創(chuàng)建插件包
首先在桌面上創(chuàng)建一個文件夾com.catchzeng.testplugin(遵守命名規(guī)范),并創(chuàng)建子文件夾及子文件如下圖,將插件的代碼復(fù)制到ios文件夾下。

插件結(jié)構(gòu)

插件結(jié)構(gòu)
二、編寫JS代碼
編寫testPlugin.js,向外部暴露testModel的testPlugin方法,這便是前端人員需要調(diào)用的接口。
var exec = require("cordova/exec");
function TestModel() {};
TestModel.prototype.testPlugin = function (success,fail,option) {
exec(success, fail, 'testPlugin', 'testWithTitle', option);
};
var testModel = new TestModel();
module.exports = testModel;
三、配置plugin.xml文件
配置plugin.xml 就是為了告訴cordova我們的文件路徑在哪,我們的oc類名是什么,oc對象名是什么,js類名及js對象名是什么等信息。這樣cordova在安裝插件時,才能找到正確的插件文件。
<?xml version="1.0" encoding="UTF-8" ?>
<plugin xmlns="http://phonegap.com/ns/plugins/1.0"
id="com.catchzeng.testplugin"
version="1.0.0">
<engines>
<engine name="cordova" version=">=3.3.0" />
</engines>
<name>testPlugin</name>
<description>測試插件</description>
<js-module src="www/testPlugin.js" name="testModel">
<clobbers target="testModel" />
</js-module>
<platform name="ios">
<source-file src="src/ios/TestPlugin.m" />
<header-file src="src/ios/TestPlugin.h" />
<source-file src="src/ios/TestViewController.m" />
<header-file src="src/ios/TestViewController.h" />
<resource-file src="src/ios/TestViewController.xib" />
<resource-file src="src/ios/test.png" />
<config-file target="config.xml" parent="/widget">
<feature name="testPlugin">
<param name="ios-package" value="TestPlugin" />
</feature>
</config-file>
</platform>
</plugin>
參數(shù)說明:
-
id="com.catchzeng.testplugin":插件id必須與文件夾名稱相同 -
<js-module src="www/testPlugin.js" name="testModel">:此處配置js所在目錄和調(diào)用的類(testModel) -
<source-file>:標(biāo)示插件所需的oc .m文件 -
<header-file>:標(biāo)示插件所需的oc .h文件 -
<resource-file>:標(biāo)示插件所需資源文件(圖片、xib資源等) -
<feature name="testPlugin"><param name="ios-package" value="TestPlugin" />:指明插件映射至ios的類名,此處的testPlugin便是對應(yīng)到testPlugin.jsexec(success, fail, 'testPlugin', 'testWithTitle', option);中的testPlugin。
四、測試插件
新建一個Cordova項目,并添加iOS平臺作為測試項目。

新建測試項目
添加插件到測試項目
cordova plugin add xxxxxx

添加插件
修改工程項目的index.html

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() {
testModel.testPlugin(alertSuccess,alertFail,["我是JS傳來的參數(shù)!"]);
}
function alertSuccess(msg) {
alert(msg);
}
function alertFail(msg) {
alert('調(diào)用OC失敗: ' + msg);
}
</script>
</head>
<body style="padding-top:50px">
<button style="font-size:17px;" onclick="testPlugin();">調(diào)用iOS插件</button> <br>
</body>
</html>
重新build iOS項目
cordova build ios

build
此時打開iOS工程后,運行程序便能得到看到插件的效果。

Plugin
將插件文件上傳到git后,前端人員也可以使用git的方式安裝我們編寫的插件
cordova plugin add https://github.com/CatchZeng/com.catchzeng.testplugin
最后附上Demo地址:https://github.com/CatchZeng/com.catchzeng.testplugin