在我的应用程序中,我需要读取存储在iPhone的Documents文件夹中的JSON文件。我看到存在一种桥接javascript和目标C的方法。我怎么能这样做?我理解我应该在目标C - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;
中使用此方法,但我应该在javascript中编写什么?我发现了这个:call objective C method from javascript,但我不明白它是如何工作的。在我的应用程序中,我要这样做:
我制作了本机应用程序并且它有效,现在我要实现从Documents文件夹中读取JSON文件的方法,任何人都可以帮我做这个操作吗?我如何从javascript中读取JSON,解析它并在html动态列表中显示结果?
谢谢
CODE UPDATE:现在我写了这段代码:
目标C片段
- (void)parseJson {
// Carico il documento JSON dalla cartella documents
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:@"data.json"];
BOOL fileExist = [[NSFileManager defaultManager] fileExistsAtPath:filePath];
if (fileExist) {
NSString *content = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
NSData *data = [content dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dictContent = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
if (dictContent) {
NSDictionary *sites = [dictContent objectForKey:@"sites"];
NSArray *site = [sites objectForKey:@"site"];
NSMutableArray *names = [[NSMutableArray alloc]init];
NSMutableArray *srcs = [[NSMutableArray alloc]init];
for (int i = 0; i < [site count]; i++) {
NSDictionary *dictData = [site objectAtIndex:i];
[names addObject:[dictData objectForKey:@"name"]];
[srcs addObject:[dictData objectForKey:@"src"]];
};
NSString *javascriptString = [NSString stringWithFormat:@"dataFromObjC([%@, %@])", names, srcs];
[self.webView stringByEvaluatingJavaScriptFromString:javascriptString];
}
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Promo" message:@"Non hai ancora salvato nessuna promozione!" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
[alert show];
}
// Faccio il parse del documento JSON
// Passo le informazioni parsate al javascript
}
在javascript中,我创建了一个名为dataFromObjC(names, srcs)
的函数。下面你会看到html代码,看看我做了什么:
Html代码
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/>
<title>Lista coupon</title>
<script src="../js/jquery-1.9.1.min.js" type="text/javascript"></script>
<script src="../js/memoria.js" type="text/javascript"></script>
<script type="text/javascript">
function dataFromObjC(names, srcs) {
alert(names);
alert(srcs);
}
</script>
<style type="text/css">
body {
background-color: #000000;
width: 100%;
height: 100%;
padding: 0;
margin: 0;
}
ul {
list-style-type: none;
padding: 5px;
}
li {
color: #FFFFFF;
font-family: sans-serif;
padding-bottom: 5px;
}
p {
color: #FFFFFF;
font-family: sans-serif;
padding: 5px;
text-align: center;
}
a {
text-decoration: none;
color: #FFFFFF;
}
</style>
</head>
<body onload="loadJson();">
<div id="header">
</div>
<div id="content">
<p>Di seguito trovi tutte le promozioni salvate</p>
<div id="list">
</div>
</div>
<div id="footer">
</div>
</body>
</html>
我希望这对解决它有用。我使用了stringByEvaluatingJavaScriptFromString
,因为我在这里发现了一个帖子来读取从目标C到javascript的数据。
答案 0 :(得分:0)
由于您只需阅读JSON,请按以下方式阅读:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES);
NSString *fullPath = [[paths lastObject] stringByAppendingPathComponent:@"myJson.json"];
NSData *jsonData = [[NSFileManager defaultManager] contentsAtPath:fullPath];
然后将其解析为nsdictionary:
id jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
再次更新: 如果你想从javascript调用obj c,你需要定义一个特定的URL,如:
http://abc.com/?key=value
然后从js:
调用它function callObjC(){
location.href='http://abc.com/?key=value';
}
然后在shouldStartLoadWithRequest中,比较请求的url和特定的URL,它们是相同的,然后执行你的功能。
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if ([[[request URL] absoluteString] hasPrefix:@"http://abc.com/"]) {
//comparing urls, if almost the same
//if you need to pass parameters to Obj C, put them in the URL as my example and explode yourself
[self anotherMethod];//your method
return NO;//skip the request, as the link is not valid or we don't want to change the webview
}
return YES;
}
你的link provided,它使用自定义协议:js-call而不是http。 它有效,但Apple不推荐它。