您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 訊息 >> iOS 相關資訊

基於 PhoneGap 3.4 的 iOS 插件開發流程

編輯:iOS 相關資訊

PhoneGap 提供了 HTML 頁面呼叫原生能力的基礎介面,但有些特殊需求無法只靠現成 API 完成,這時就需要自訂插件。

建立插件類別

在 iOS 中,PhoneGap 插件通常會繼承 CDVPlugin。以下是一個簡單的登入插件:

@interface CDVLogin : CDVPlugin
- (void)login:(CDVInvokedUrlCommand *)command;
@end

實作原生邏輯

在實作中,可以從 command.arguments 取得 JavaScript 傳來的參數,再回傳結果。

- (void)login:(CDVInvokedUrlCommand *)command {
    NSString *param = command.arguments.firstObject;
    BOOL success = [self loginSystem:param];

    CDVPluginResult *result = [CDVPluginResult resultWithStatus:success ? CDVCommandStatus_OK : CDVCommandStatus_ERROR
                                              messageAsString:success ? @"YES" : @"NO"];

    [self.commandDelegate sendPluginResult:result callbackId:command.callbackId];
}

註冊插件

完成類別後,需要在 config.xml 中註冊,讓 PhoneGap 知道如何找到這個插件。通常會設定名稱與對應的 iOS 類別名稱。

JavaScript 呼叫

前端可以透過 cordova.exec 呼叫原生方法。

function callNativePlugin(param) {
    var success = function(result) {
        console.log(result);
    };

    var fail = function(error) {
        console.log(error);
    };

    cordova.exec(success, fail, "Login", "login", [param]);
}

小結

PhoneGap 插件開發的核心流程是:建立 CDVPlugin 子類、實作方法、回傳 CDVPluginResult、在 config.xml 註冊,最後由 JavaScript 呼叫。掌握這幾個步驟後,就能把原生能力包裝成網頁可使用的介面。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved