在开始Cordova插件的时候遇到了一个有意思的问题,我在GitHub上寻找的一个iOS上的包用的是Swift
+ Objective-C
,于是让我们来看看他们是怎么结合到一起的。
我们只需要简单地修改下plugin.xml
,然后在代码中定义一个Bridgin-Header.h
文件即可,如下代码所示:
<platform name="ios">
<info>
open xcode go into settings change `deployment target` to 7.0 or above and add `[Project Name]/Plugins/com.example.hello/Bridging-Header.h` to Objective-c Bridging Header under the Swift Compiler - Code Generation options
</info>
<config-file target="config.xml" parent="/*">
<feature name="Hello">
<param name="ios-package" value="HWPHello"/>
</feature>
</config-file>
<header-file src="src/ios/Bridging-Header.h" />
<source-file src="src/ios/Hello.swift"/>
</platform>
在头文件中,我们引入将要给Swift用的头文件
#import <Cordova/CDV.h>
在同目录下的Hello.swift
便可直接使用:
import Foundation
@objc(HWPHello) class Hello : CDVPlugin {
func greet(command: CDVInvokedUrlCommand) {
var message = command.arguments[0] as String
var pluginResult = CDVPluginResult(status: CDVCommandStatus_OK, messageAsString: "Hello \(message)")
commandDelegate.sendPluginResult(pluginResult, callbackId:command.callbackId)
}
}
这时如https://github.com/edewit/cordova-plugin-hello/tree/swift中所说,我们还需要一些特别的步骤,后面我们可以用代码来解决。
go into settings change deployment target to 7.0 or above and add
/Plugins/com.example.hello/Bridging-Header.h to Objective-c Bridging Header under the Swift Compiler - Code Generation options Finally add the following LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks";
这一点也适用于一些复杂的例子,如我在试验的[https://github.com/phodal/coap-cordova-plugin](https://github.com/phodal/coap-cordova-plugin)
我的xml是这样的:
<platform name="ios">
<hook type="c" src="hooks/add_swift_support.js" />
<config-file target="config.xml" parent="/widget">
<feature name="Coap">
<param name="ios-package" value="HWCoapPlugin" />
</feature>
</config-file>
<header-file src="src/ios/GCDAsyncUdpSocket.h"/>
<source-file src="src/ios/GCDAsyncUdpSocket.m"/>
<header-file src="src/ios/CoAP-Bridging-Header.h"/>
<source-file src="src/ios/SCClient.swift"/>
<source-file src="src/ios/SCMessage.swift"/>
<source-file src="src/ios/SCServer.swift"/>
<source-file src="src/ios/Coap.swift"/>
</platform>
后面的Coap.swift
需要调用GCDAsyncUdpSocket
里面的函数,所以我们需要定义在CoAP-Bridging-Header.h
中:
#import <Cordova/CDV.h>
#import "GCDAsyncUdpSocket.h"
但是要是每次都这样就太麻烦了,于是网上出现了一个名为add_swift_support.js
的脚本,用来自动化上面那些步骤。
围观我的Github Idea墙, 也许,你会遇到心仪的项目