1

在我的应用程序中,我需要读取存储在 iPhone 的 Documents 文件夹中的 JSON 文件。我看到存在一种桥接 javascript 和目标 C 的方法。我该怎么做?我知道我应该在目标 C 中使用这种方法- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;,但是我应该用 javascript 写什么?我发现了这个:call objective C method from javascript,但我不明白它是如何工作的。在我的应用程序中,我必须这样做:

  1. 从移动网站获得报价(我制作了一些小型移动网站)
  2. 我将移动站点本地存储在 iPhone 的 Documents 文件夹中
  3. 我生成一个 JSON 文件来保存商品的名称、路径和到期日期。我将此 JSON 存储在 iPhone 的 Documents 文件夹中
  4. 我的应用程序有一个“存档”视图控制器,我在其中加载了一个移动站点,我将在其中通过读取创建的 JSON 列出存储在设备中的所有报价

我制作了本机应用程序并且它可以工作,现在我必须实现从 Documents 文件夹中读取 JSON 文件的方法,谁能帮我做这个操作?如何从 javascript 中读取 JSON,对其进行解析并在 html 动态列表中显示结果?

谢谢

代码更新:现在我写了这段代码:

目标 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 的帖子。

4

1 回答 1

0

As you need to read JSON only, then read it by:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                     NSUserDomainMask,
                                                     YES);

NSString *fullPath = [[paths lastObject] stringByAppendingPathComponent:@"myJson.json"];
NSData *jsonData = [[NSFileManager defaultManager] contentsAtPath:fullPath];

then parse it to nsdictionary:

id jsonDict = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];

Updated Again: If you want to call obj c from javascript, you need to define a specific URL like:

http://abc.com/?key=value

Then call it from js:

function callObjC(){
  location.href='http://abc.com/?key=value';
}

Then in shouldStartLoadWithRequest, compare the request's url and the specific URL, it they are the same then do your function.

- (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;
}

Your link provided, it uses a self-defined protocol: js-call rather than http. It works, but Apple do not recommend it.

于 2013-08-01T08:03:53.770 回答