0%

phoneGap在iOS上给JS传值方法

iOS端:

在要传值页面(比如城市列表)中实现如下方法:

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    //通知名仅供测试,根据项目修改
    [[NSNotificationCenter defaultCenter] postNotificationName:@"post2JS" object:nil];
}

在MainViewController.m的viewDidLoad方法中增加:

//给js传值测试
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(post2JS) name:@"post2JS" object:nil];

并实现:

- (void)post2JS
{
//使用alert注意此处最好延迟执行,否则可能程序卡死,未测试非延迟情况下传值问题,延迟执行成功
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//        [self.webView stringByEvaluatingJavaScriptFromString:@"alert('hello')"];
       [self.webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"postStr('%@');",@“要传递的值"]];

    });
}    

JS端:

在需要接受参数值的js界面实现如下方法:

function postStr(str1){
    alert(str1);    //接收到的值”;
    	//...code
}    

参考链接:http://www.yelanxiaoyu.com/app/phonegap开发/phonegap-ios开发-oc调用js传递参数并获得返回值.html