iOS Plugins
iOS Plugins
This section provides details for how to implement native plugin code on the iOS platform. Before reading this, see Application Plugins for an overview of the plugin's structure and its common JavaScript interface. This section continues to demonstrate the sample echo plugin that communicates from the Cordova webview to the native platform and back.
An iOS plugin is implemented as an Objective-C class that extends the CDVPlugin class. For JavaScript's exec method's service parameter to map to an Objective-C class, each plugin class must be registered as a <feature> tag in the named application directory's config.xml file.
Plugin Class Mapping
The JavaScript portion of a plugin uses the cordova.exec method as follows:
exec(<successFunction>, <failFunction>, <service>, <action>, [<args>]);
This marshals a request from the UIWebView to the iOS native side, effectively calling the action method on the serviceclass, with the arguments passed in the args array.
Specify the plugin as a <feature> tag in your Cordova-iOS application's project's config.xml file, using the plugin.xmlfile to inject this markup automatically, as described in Application Plugins:
<feature name="LocalStorage">
<param name="ios-package" value="CDVLocalStorage" />
</feature>
The feature's name attribute should match what you specify as the JavaScript exec call's service parameter. The valueattribute should match the name of the plugin's Objective-C class. The <param> element's name should always be ios-package. If you do not follow these guidelines, the plugin may compile, but Cordova may still not be able to access it.
Plugin Initialization and Lifetime
One instance of a plugin object is created for the life of each UIWebView. Plugins are ordinarily instantiated when first referenced by a call from JavaScript. Otherwise they can be instantiated by setting a param named onload to true in the config.xml file:
<feature name="Echo">
<param name="ios-package" value="Echo" />
<param name="onload" value="true" />
</feature>
There is no designated initializer for plugins. Instead, plugins should use the pluginInitialize method for their startup logic.
Plugins with long-running requests, background activity such as media playback, listeners, or that maintain internal state should implement the onReset method to clean up those activities. The method runs when the UIWebView navigates to a new page or refreshes, which reloads the JavaScript.
Writing an iOS Cordova Plugin
A JavaScript call fires off a plugin request to the native side, and the corresponding iOS Objective-C plugin is mapped properly in the config.xml file, but what does the final iOS Objective-C plugin class look like? Whatever is dispatched to the plugin with JavaScript's exec function is passed into the corresponding plugin class's action method. A plugin method has this signature:
- (void)myMethod:(CDVInvokedUrlCommand*)command
{
CDVPluginResult* pluginResult = nil;
NSString* myarg = [command.arguments objectAtIndex:0];
if (myarg != nil) {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK];
} else {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"Arg was null"];
}
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
For more details, see [CDVInvokedUrlCommand.h](https://github.com/apache/cordova-ios/blob/master/CordovaLib/Classes/CDVInvokedUrlCommand.h), [CDVPluginResult.h](https://github.com/apache/cordova-ios/blob/master/CordovaLib/Classes/CDVPluginResult.h), and[CDVCommandDelegate.h](https://github.com/apache/cordova-ios/blob/master/CordovaLib/Classes/CDVCommandDelegate.h).
iOS CDVPluginResult Message Types
You can use CDVPluginResult to return a variety of result types back to the JavaScript callbacks, using class methods that follow this pattern:
+ (CDVPluginResult*)resultWithStatus:(CDVCommandStatus)statusOrdinal messageAs...
You can create String, Int, Double, Bool, Array, Dictionary, ArrayBuffer, and Multipart types. You can also leave out any arguments to send a status, or return an error, or even choose not to send any plugin result, in which case neither callback fires.
Note the following for complex return values:
- messageAsArrayBuffer expects NSData* and converts to an ArrayBuffer in the JavaScript callback. Likewise, any ArrayBuffer the JavaScript sends to a plugin are converted to NSData*.
- messageAsMultipart expects an NSArray* containing any of the other supported types, and sends the entire array as the arguments to your JavaScript callback. This way, all of the arguments are serialized or deserialized as necessary, so it is safe to return NSData* as multipart, but not as Array/Dictionary.
Echo iOS Plugin Example
To match the JavaScript interface's echo feature described in Application Plugins, use the plugin.xml to inject a featurespecification to the local platform's config.xml file:
<platform name="ios">
<config-file target="config.xml" parent="/*">
<feature name="Echo">
<param name="ios-package" value="Echo" />
</feature>
</config-file>
</platform>
Then we would add the following Echo.h and Echo.m files to the Plugins folder within the Cordova-iOS application directory:
/********* Echo.h Cordova Plugin Header *******/
#import <Cordova/CDV.h>
@interface Echo : CDVPlugin
- (void)echo:(CDVInvokedUrlCommand*)command;
@end
/********* Echo.m Cordova Plugin Implementation *******/
#import "Echo.h"
#import <Cordova/CDV.h>
@implementation Echo
- (void)echo:(CDVInvokedUrlCommand*)command
{
CDVPluginResult* pluginResult = nil;
NSString* echo = [command.arguments objectAtIndex:0];
if (echo != nil && [echo length] > 0) {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:echo];
} else {
pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
}
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
@end
The necessary imports at the top of the file extends the class from CDVPlugin. In this case, the plugin only supports a single echo action. It obtains the echo string by calling the objectAtIndex method get the first parameter of the arguments array, which corresponds to the arguments passed in by the JavaScript exec() function.
It checks the parameter to make sure it is not nil or an empty string, returning a PluginResult with an ERROR status if so. If the parameter passes the check, it returns a PluginResult with an OK status, passing in the original echo string. Finally, it sends the result to self.commandDelegate, which executes the exec method's success or failure callbacks on the JavaScript side. If the success callback is called, it passes in the echo parameter.
iOS Integration
The CDVPlugin class features other methods that your plugin can override. For example, you can capture the pause, resume, app terminate and handleOpenURL events. See the CDVPlugin.h and CDVPlugin.m class for guidance.
Threading
Plugin methods ordinarily execute in the same thread as the main interface. If your plugin requires a great deal of processing or requires a blocking call, you should use a background thread. For example:
- (void)myPluginMethod:(CDVInvokedUrlCommand*)command
{
// Check command.arguments here.
[self.commandDelegate runInBackground:^{
NSString* payload = nil;
// Some blocking logic...
CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:payload];
// The sendPluginResult method is thread-safe.
[self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}];
}
Debugging iOS Plugins
To debug on the Objective-C side, you need Xcode's built-in debugger. For JavaScript, on iOS 5.0 you can use Weinre, an Apache Cordova Project or iWebInspector, a third-party utility. For iOS 6, you can attach Safari 6.0 to the app running within the iOS 6 Simulator.
Common Pitfalls
- Don't forget to add your plugin's mapping to config.xml. If you forget, an error is logged in the Xcode console.
- Don't forget to add any hosts you connect to in the whitelist, as described in Domain Whitelist Guide. If you forget, an error is logged in the Xcode console.
iOS Plugins的更多相关文章
- iOS 混合开发之 Cordova 实践
在15年时,之前公司使用 Cordova 做混合开发使用,后来公司没有用到了,现在重新记录下. Cordova (官网:http://cordova.apache.org/)简介: Apache Co ...
- Cordova学习(一) 环境搭建
一.什么是cordova Cordova提供了一组设备相关的API,通过这组API,移动应用能够以JavaScript访问原生的设备功能,如摄像头.麦克风等. Cordova还提供了一组统一的Java ...
- mobile web retina 下 1px 边框解决方案
本文实际上想说的是ios8下 1px解决方案. 1px的边框在devicePixelRatio = 2的retina屏下会显示成2px,在iphone 6 plug 下,更显示成3px.由其影响美感. ...
- Cordova CLI源码分析(一)——简介
本系列文章分析基于node.js的命令行工具Cordova CLI,所以如果对node.js基础不是很了解,建议参考http://nodejs.gamesys.net/node-js提供的基础教程 文 ...
- ionic4+angular6 混合移动开发 capacitor cordova
首先要更新或者安装 ionic cli npm install -g ionic 创建项目 ionic start ionic-angular tabs --type=angular –type=an ...
- 自定义 Cordova插件详解
一.Cordova的基础点 在混合式应用中,我们通过现有的Cordova插件,可以轻松的在 H5 上调用手机native的功能.现有的Cordova插件能满足平时大部分的开发需求,然而,有时候找不到合 ...
- 自定义Cordova插件详解
一.Cordova的基础点 在混合式应用中,我们通过现有的Cordova插件,可以轻松的在 H5 上调用手机native的功能.现有的Cordova插件能满足平时大部分的开发需求,然而,有时候找不到合 ...
- 再谈mobile web retina 下 1px 边框解决方案
本文实际上想说的是ios8下 1px解决方案. 1px的边框在devicePixelRatio = 2的retina屏下会显示成2px,在iphone 6 plug 下,更显示成3px.由其影响美感. ...
- Ionic3 demo TallyBook 实例1
1.创建项目 ionic start TallyBook blank 创建一个空的项目 ionic cordova platform add android 添加andorid平台 io ...
随机推荐
- NHibernate总结
NHibernate总结 现在的项目中数据访问使用的是NHibernate的一个ORM框架,小弟也是在后期加入项目组,之前对NHibernate就一直没有接触过,所以一直在学习NHibernate,都 ...
- U盘安装CentOS 6.4 + Windows 7双系统 (Windows 7下安装 CentOS 6.4)
最近在看<鸟哥私房菜:基础学习篇>,觉得很不错,想要装个windows 7 和 CentOS 6.4 双系统,在网上找了很多教程,觉得乱七八糟的,弄得很复杂,而且很多都不是很完整,对于新手 ...
- linux sendEmail工具的安装使用
1.sendEmail的主页http://caspian.dotconf.net/menu/Software/SendEmail/ 下载地址wget http://caspian.dotconf.ne ...
- JAVA的abstract修饰符 && 接口interface用法 && 抽象类和interface的差别
abstract修饰符可以修饰类和方法. (1)abstract修饰类,会使这个类成为一个抽象类,这个类将不能生成对象实例,但可以做为对象变量声明的类型(见后面实例),也就是编译时类型.抽象类就相当于 ...
- C语言之循环结构 for(一)
一 for循环的介绍 语法: for(表达式1;表达式2;表达式3){ 循环体; } 循环步骤: A.执行表达式1,执行完毕跳转到B B.判断表达式2的结果是否为真,如果为真,跳转到C,否则跳转到E ...
- 【高性能】生成唯一时间戳ID,1毫秒预计能生成1000个
凡事涉及到高性能貌似都是高大上的东西,所以嘛我也试试:其实这个时间戳ID的生成主要为了解决我们公司内部的券号生成,估计有小伙伴认为券号生成有这么麻烦嘛,搞个自增ID完全可以用起来,或者时间取毫微米时间 ...
- PHPWAMP开启php_stomp.dll的具体方式,php5.6开启stomp的图解过程
友情提示:其他版本,方式一样的,大家依样画葫芦即可. 首先下载PHP 扩展php_stomp.dll文件,在php官方网站搜索"Stomp",搜索后,如下图 如下图点击" ...
- js如何判断是否在iframe中
JS代码://方式一 if (self.frameElement && self.frameElement.tagName == "IFRAME") { alert ...
- app外包开发注意事项大全『最新』
随着移动互联网的高速发展,很多互联网创业公司或传统向互联网转型的公司都急需发开一款app软件,多数公司会选择让外包公司来开发.问题来了,App外包市场鱼龙混杂,我们要如何在这里面选择一个靠谱的公司,这 ...
- 七、rdd究竟是什么
RDD是个抽象类,定义了诸如map().reduce()等方法,但实际上继承RDD的派生类一般只要实现两个方法: def getPartitions: Array[Partition] def com ...