如何使用nsarray将数据集合传递给Objective C代码中的javascript函数

时间:2014-07-25 06:56:13

标签: javascript ios objective-c

我试图将html和本地目标c代码一起渲染。我的目的是识别一个html元素(假设一个按钮)并按下按钮将调用本机(Objective C)警报。而且我已成功实现了这一点。现在,我正在得到一个Json。现在从Json开始,我想使用从Objective C调用的JS函数将两个对象发送回Javascript。我的问题是如果有任何特殊字符(例如\,'&),我无法调用JS函数#39;等)。当我从String中删除所有特殊字符时,我可以调用该函数。

这是我的代码

    int i;
    for (i=0; i<[arr count]; i++)
     {
      image_path=[NSString stringWithFormat:@"http://new.my.anandabazar.com%@",[[arr     objectAtIndex:i]valueForKey:@"imagepath"]];
             str_title=[NSString stringWithFormat:@"%@ <img src=\"%@\">",[[arr objectAtIndex:i]valueForKey:@"title"], image_path];

       NSString *newVar =[[str_title componentsSeparatedByCharactersInSet:[[NSCharacterSet letterCharacterSet] invertedSet]] componentsJoinedByString:@""];
            NSLog(@"%@",newVar);

             [array_data addObject:newVar];

    - (void)webViewDidFinishLoad:(UIWebView *)webView
    {
        NSString *arrayStr = [array_data componentsJoinedByString:@";"];
        NSString *jsFunc = [NSString stringWithFormat:@"data_abc(['%@'])", arrayStr];

        NSLog(@"now array is %@",[NSString stringWithFormat:@"data_abc(['%@'])", arrayStr]);
        [webview stringByEvaluatingJavaScriptFromString:jsFunc];
    }

这是我的HTML代码:

 <html>
    <head>

    </head>
    <body>

        <ul id="snippetid">



        </ul>
     <script>
          function data_abc(str)
    //      function data_abc()
          {


              var new_str=str;
       document.getElementById('snippetid').innerHTML = str;
                alert(new_str);

          }

     </script>


    <form>
    <input type="checkbox" name="vehicle" value="News">News<br>
    <input type="checkbox" name="vehicle" value="Articles">Articles <br>

    <input type='button' value="Do something in iOS" onclick='window.location="callmycode:cmd=showAlert&var=myVar"'/>


    </form>
    </body>
    </html>

请帮助我......谢谢

1 个答案:

答案 0 :(得分:0)

尝试使用NSJSONSerialization:

    NSArray *array_str = @[str_title];

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:array_str options:NSJSONWritingPrettyPrinted error:nil];
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSString *js = [NSString stringWithFormat:@"data_abc(%@)", jsonString];
    NSLog(@"%@", js);

    [webview stringByEvaluatingJavaScriptFromString:js];