PhoneGap開發IOS,JS調用IOS方法/phoneGap插件開發——FakeMr
廢話不說phoneGap是什麼很少介紹,官方網站: http://phonegap.com/
以前寫過phoneGap開發Android插件教程: http://my.oschina.net/jgy/blog/145385 javascript
這個是目錄結構 java
在Plugins下新建文件(在Plugins上右鍵-new file選擇Objective-c class)輸入名字(CDVMyPlugin) next…… ios
這世間你會發如今Plugins下面有兩個文件,分別是:CDVMyPlugin.h和CDVMyPlugin.m 數組
#import <Foundation/Foundation.h> #import <Cordova/CDVPlugin.h> @interface CDVMyPlugin : CDVPlugin @property (nonatomic, copy) NSString* callbackID; // Instance Method - (void) print:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options; @end
#import "CDVMyPlugin.h" @implementation CDVMyPlugin @synthesize callbackID; -(void)print:(NSMutableArray*)arguments withDict:(NSMutableDictionary*)options { // 這是classid,在下面的PluginResult進行數據的返回時,將會用到它 self.callbackID = [arguments pop]; // 獲得Javascript端發送過來的字符串 NSString *stringObtainedFromJavascript = [arguments objectAtIndex:0]; // 建立咱們要返回給js端的字符串 NSMutableString *stringToReturn = [NSMutableString stringWithString: @"我是返回的:"]; [stringToReturn appendString: stringObtainedFromJavascript]; // Create Plugin Result CDVPluginResult* pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString: stringToReturn]; NSLog(@ "%@",stringToReturn); // 檢查發送過來的字符串是否等於"HelloWorld",若是不等,就以PluginResult的Error形式返回 if ([stringObtainedFromJavascript isEqualToString:@"HelloWorld"] == YES){ // Call the javascript success function [self writeJavascript: [pluginResult toSuccessCallbackString:self.callbackID]]; } else{ // Call the javascript error function [self writeJavascript: [pluginResult toErrorCallbackString:self.callbackID]]; } }
//調用IOS方法插件 var MyIOSPlugin = { /** * 調用IOS方法 * @param method 要調用IOS插件的方法名 * @param parameter 參數[數組] * @param success 成功回調 * @param fail 失敗回調 * @returns {*} */ nativeFunction: function(method, parameter, success, fail) { return Cordova.exec(success, fail, "MyPlugin", method, parameter); } };
MyIOSPlugin.nativeFunction("print",['HelloWorld'], function(result) { // alert("Success: \r\n"+result); }, function(error) { // alert("Error: \r\n"+error); } );
<feature name="MyPlugin"> <param name="ios-package" value="CDVMyPlugin" /> </feature>OVER!
最後:以上是本人測試成功後以及經驗分享,歡迎吐槽交流!嘎嘎~~~~ app
原文連接:http://my.oschina.net/jgy/blog/175643 測試
做者:FakeMr 郟高陽 ❤犒勞一杯咖啡❤