插件配置流程:
1. 写OC插件类TestPlugin(类名自定义),类中方法根据需求改写。
TestPlugin.h:
#import <Cordova/CDV.h>
#import "ASIFormDataRequest.h"
@interface TestPlugin : CDVPlugin <ASIHTTPRequestDelegate>
-(void)test:(CDVInvokedUrlCommand*)command;
@end
TestPlugin.m:
#import "TestPlugin.h"
@implementationTestPlugin
- (void)test:(CDVInvokedUrlCommand*)command
{
//command是从JS端传递过来的参数
NSString *url = [command argumentAtIndex:0 withDefault:@""];
NSDictionary *postBody= [command argumentAtIndex:1 withDefault:@""];
ASIFormDataRequest *requestForm = [[ASIFormDataRequest alloc] initWithURL:[NSURL URLWithString:url]];
//设置需要POST的数据
[requestForm setPostValue:[postBody objectForKey:@"username"] forKey:@"username"];
[requestForm setPostValue:[postBody objectForKey:@"password"] forKey:@"password"];
[requestForm startSynchronous];
//输入返回的信息
NSString* dateString =[requestForm responseString];
//数据返回到JS端
[self.commandDelegate sendPluginResult:[CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString: dateString] callbackId:command.callbackId];
}
@end
2. 在Staging中的config.xml文件的widget标签中添加
<feature name="TestPlugin">
<param name="ios-package"value="TestPlugin" />
</feature>
目的是告诉JS端要调用的OC类是哪个。
3. 在JS中调用
cordova.exec(success,failed,OC类名,OC类中要调用的方法名,JS要传到OC的参数);
例:
cordova.exec(function (res) {
alert(res);
res = JSON.parse(res);
},function (err) {
err = JSON.parse( err );
},"TestPlugin","test",['http://qianjing.test.jvtd.cn/login.php',{username:$scope.loginData.username,password:$scope.loginData.password}]);