1. 程式人生 > >ionic2中利用自定義cordova外掛(Plugin)ts調iOS原生的值(iOS原生的值傳給ts)

ionic2中利用自定義cordova外掛(Plugin)ts調iOS原生的值(iOS原生的值傳給ts)

一、安裝外掛

1、安裝plugman

$npm install -g plugman 如果出現下面的錯誤,在前面加"sudo"(sudo可以將許可權提升到超級使用者級別,即Windows中的管理員),換成“sudo npm install -g plugman”,另外還能避免下面第3步出現問題 (plugman的所有命令可用“$plugman --help”檢視)

2、生成外掛

plugman create --name <pluginname> --plugin_id <pluginid> --plugin_version 0.0.1。例如,

$plugman create --name MyPlugin --plugin_id com.plugin.myPlugin --plugin_version 

0.0.1,

注意,此時生成的外掛存放都在根目錄,如圖。如果存放在其他目錄可以在最後面加" -path 檔名",如plugman create --name MyPlugin --plugin_id com.plugin.myPlugin --plugin_version 0.0.1 -path MP。

這時候src檔案裡面是空

3、新增平臺

$cd MyPlugin

$plugman platform add --platform_name ios

如果出現“can't find a plugin.xml.  Are you in the plugin?”,這是因為你的操作許可權低,說明你在第1步沒有用sudo

,所以再執行第1步“sudo npm install -g plugman”。

此時再看,src資料夾裡面增加了iOS檔案。注意,如果只生成了iOS資料夾,沒有.m檔案,就手動刪除iOS檔案,再plugman platform remove --platform_name iOS,這樣就徹底刪除了,如果還不行,就要修改更新一下你的環境了,包含node.js、npm、ionic,再執行plugman platform add --platform_name ios就可以了。



4、安裝外掛

首先,找到MyPlugin的路徑

$pwd MyPlugin

拿到路徑


 $ionic plugin add (你拿到的外掛路徑)。

新環境可能會報“Error: Invalid Plugin! /Users/使用者名稱/專案名/外掛名 needs a valid package.json”錯誤,這需要手動新增package.json檔案

$sudo plugman createpackagejson (外掛路徑)

然後檔案中就會出現package.json檔案了,然後再執行$ionic plugin add (你拿到的外掛路徑),就可以了。

檢視plugins資料夾裡面多了一個名為com.plugin.myPlugin的資料夾


二、外掛呼叫

1、ts檔案

在src/pages裡面找到需要呼叫原生的.ts檔案
先在@Component之前,import之後,新增“declare let cordova: any;“,否則,不能呼叫cordova。 先設定.html檔案,使其可以展示結果
<p id="testde">
    Take a look at the <code>src/pages/</code> directory to add or change tabs,
    update any existing page or create new pages.
  </p>
  <button ion-button="" color="secondary" (click)="ttfunc()">Secondary</button>

.ts檔案
ttfunc(){
  cordova.plugins.MyPlugin.coolMethod("傳來的引數",
  function (msg) {
    alert('成功');
    console.log(msg);
    document.getElementById("testde").innerHTML=msg;
  },
  function (msg) {
    alert('失敗');
  });
}

 ttfunc()這個方法就是ts這邊的呼叫,cordova.plugins.MyPlugin.coolMethod這個方法中MyPlugin是外掛名,coolMethod是方法名,去外掛中檢視MyPlugin.js就明白了。


在這個地方值得一提的是,ts中的這個方法用在js裡面基本也是可以的。

2、iOS原生檔案

找到檔案開啟

iOS原生的主要問題是,怎麼把資料傳給外掛。我測試一下,個人覺得屬性傳值和通知傳值都不合適,單例傳值還是比較靠譜的,其他傳值方式大家可以自己試試。

單例自己封裝或者用nsuserdefaults都可以,原理就是先把資料本地化,再賦值給外掛。

#import <Foundation/Foundation.h>

@interface DataSingle : NSObject
//根據自己的需要自定義你需要的型別
@property(nonatomic,copy)NSString *dataStr;
@property(nonatomic,strong)NSArray *dataArr;
@property(nonatomic,strong)NSDictionary *dataDic;
    
+(instancetype)shareDataSingle;
    
    
@end

如圖,iOS的外掛類只生成了.m檔案

以下是MyPlugin.m檔案內容
/********* MyPlugin.m Cordova Plugin Implementation *******/

#import <Cordova/CDV.h>
#import "DataSingle.h"

@interface MyPlugin : CDVPlugin {
  // Member variables go here.
}

- (void)coolMethod:(CDVInvokedUrlCommand*)command;
@end

@implementation MyPlugin

  
- (void)coolMethod:(CDVInvokedUrlCommand*)command
{
    NSLog(@"----coolmethod-----");
    [self.commandDelegate runInBackground:^{
        CDVPluginResult* pluginResult = nil;
        DataSingle *ds=[DataSingle shareDataSingle];
        NSLog(@"===========dataStr==%@==========",ds.dataStr);
        NSString* echo =[command.arguments objectAtIndex:0];//echo:ts端傳來的引數
        NSLog(@"-----------echo===%@",echo);
        NSUserDefaults *usr=[NSUserDefaults standardUserDefaults];
        if (echo != nil && [echo length] > 0) {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:ds.dataStr];//ds.dataStr:原生資料,傳給ts
            pluginResult=[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:[usr objectForKey:@"text"]];
        } else {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR];
        }
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }];
}
@end

以上就是iOS原生傳值給ts的整個流程。 注意,檔名儘可能避免有空格!!!

(歡迎指正!)

轉發請標明出處!