如何从Objective C方法将包含JSON的JSON NSString传递给Javascript方法 [英] How to Pass JSON NSString containing JSON to a Javascript Method from an Objective C method

查看:118
本文介绍了如何从Objective C方法将包含JSON的JSON NSString传递给Javascript方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个要求目标C代码消耗 WebService 以及<$ c中收到的响应$ c> JSON格式必须作为参数传递给 javascript 方法进行进一步处理。我正在使用 UIWebView 在处理 JSON响应后将显示相应的结果。
当我尝试将JSON字符串传递给<$ c时出现问题$ c> Javascript method.Javascript方法不会简单地接受输入。

I have a requirement where the objective C code should consume the WebService and the response received in JSON format has to be passed as an argument to a javascript method for further processing.I am using UIWebView which will display the appropriate results after processing JSON response. The issue arises when i try to pass the JSON string to Javascript method.Javascript method does not simply accept the input.

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    NSString *responseString = [[NSString alloc] initWithBytes:[resultData bytes] length:[resultData length] encoding:NSUTF8StringEncoding];
    NSLog(@"%@",responseString);
    [self returnResponseToJavaScriptMethods:responseString];
}


-(void)returnResponseToJavaScriptMethods:(NSString*)theResponse{
    [viewMainWebView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"retrieveServerResponse('%@')",theResponse]];
}

有什么我错过的吗?使用相同的方法正确传递简单字符串。

Is there anything that I am missing out ?? Simple strings are getting passed properly using the same approach.

更新
编码 responseData UTF8StringEncoding 诀窍。

[theResponse stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]


推荐答案

你可能需要URL-escape将JSON字符串发布到javascript之前的JSON字符串。

You probably need to URL-escape the JSON string before posting it to the javascript.

尝试更改:

-(void)returnResponseToJavaScriptMethods:(NSString*)theResponse{
  [viewMainWebView stringByEvaluatingJavaScriptFromString:
  [NSString stringWithFormat:@"retrieveServerResponse('%@')",theResponse]];
}

-(void)returnResponseToJavaScriptMethods:(NSString*)theResponse{
  [viewMainWebView stringByEvaluatingJavaScriptFromString:
  [NSString stringWithFormat:@"retrieveServerResponse('%@')",
 [theResponse stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]]];
} 

看看这对你有帮助。但请注意,有更好的(或更可靠的)方法来转义字符串,例如在此答案中给出的方法:如何对字符串进行URL编码

And see if that helps you. Note, however, that there are better (or more surefire) ways to escape a string, for example the one given at this answer: How do I URL encode a string

这篇关于如何从Objective C方法将包含JSON的JSON NSString传递给Javascript方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆