ionic JS与OC互操作插件

插件配置流程:

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}]);

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值