Я выполнил инструкции с этого сайта, http://moduscreate.com/writing-a-cordova-plugin-in-swift-for-ios/, для создания моих собственных плагинов cordova для платформы iOS. Во-первых, я установил плагина и создал новый плагин. Это мой plugin.xml:Написание плагина Cordova/Ionic Swift
<?xml version='1.0' encoding='utf-8'?>
<plugin id="com-moduscreate-plugins-echoswift" version="0.0.1" xmlns="http://apache.org/cordova/ns/plugins/1.0" xmlns:android="http://schemas.android.com/apk/res/android">
<name>ModusEchoSwift</name>
<js-module name="ModusEchoSwift" src="www/ModusEchoSwift.js">
<clobbers target="modusechoswift" />
</js-module>
<platform name="ios">
<config-file target="config.xml" parent="/*">
<feature name="ModusEchoSwift">
<param name="ios-package" value="ModusEchoSwift" />
</feature>
</config-file>
<source-file src="src/ios/ModusEchoSwift.swift" />
</platform>
</plugin>
Вот мой JS файл для плагина, т.е. ModusEchoSwift.js:
var exec = require('cordova/exec');
exports.echo = function(arg0, success, error) {
exec(success, error, "ModusEchoSwift", "echo", [arg0]);
};
exports.echojs = function(arg0, success, error) {
if (arg0 && typeof(arg0) === 'string' && arg0.length > 0) {
success(arg0);
} else {
error('Empty message!');
}
};
И это мой родной Swift класс, т.е. ModusEchoSwift.swift:
@objc(ModusEchoSwift) class ModusEchoSwift : CDVPlugin {
func echo(command: CDVInvokedUrlCommand) {
var pluginResult = CDVPluginResult(
status: CDVCommandStatus_ERROR
)
let msg = command.arguments[0] as? String ?? ""
if msg.characters.count > 0 {
/* UIAlertController is iOS 8 or newer only. */
let toastController: UIAlertController =
UIAlertController(
title: "",
message: msg,
preferredStyle: .Alert
)
self.viewController?.presentViewController(
toastController,
animated: true,
completion: nil
)
let duration = Double(NSEC_PER_SEC) * 3.0
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
Int64(duration)
),
dispatch_get_main_queue(),
{
toastController.dismissViewControllerAnimated(
true,
completion: nil
)
}
)
pluginResult = CDVPluginResult(
status: CDVCommandStatus_OK,
messageAsString: msg
)
}
self.commandDelegate!.sendPluginResult(
pluginResult,
callbackId: command.callbackId
)
}
}
Это файлы в моем плагине. Теперь я пытаюсь показать простое предупреждение с помощью этого плагина в моем ионном проекте. У меня есть простой index.html прямо сейчас, где я хочу отобразить предупреждение, вот оно:
<ion-pane>
<ion-header-bar class="bar-stable">
<h1 class="title">Ionic Blank Starter</h1>
</ion-header-bar>
<ion-content>
<div ng-controller="myController">
Hello {{user}}
</div>
</ion-content>
</ion-pane>
А вот мой контроллер:
.controller('myController', function($scope){
console.log("Ok");
$scope.user = "kAy";
ModusEchoSwift.echo('Plugin Ready!', function(msg) {
console.log("Success");
},
function(err) {
console.log("Error");
}
);
})
Вот в этом контроллер, я все время получаю ошибку, что ModusEchoSwift не определен, чего я не понимаю! Может ли кто-нибудь сказать мне, как использовать функцию моего плагина в моем существующем ионном проекте?
Вы включили файл cordova.js в свой HTML? – Gandhi
У меня есть, я не думаю, что проблема –
Является ли ваш плагин включенным в папку плагинов платформы iOS? Также в вашей папке плагинов проекта ваша пользовательская запись плагина доступна в файле ios.json? – Gandhi