【问题标题】:Read JSON file from documents folder iOS with javascript使用 javascript 从文档文件夹 iOS 中读取 JSON 文件
【发布时间】:2013-08-02 00:41:56
【问题描述】:

在我的应用程序中,我需要读取存储在 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 动态列表中?

谢谢

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

Objective C sn-p

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

【问题讨论】:

    标签: javascript iphone json directory


    【解决方案1】:

    由于您只需要读取 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 不推荐它。

    【讨论】:

    • 好的,我知道了。但我必须用 javascript 来做......我该怎么做?
    • 你觉得这个link怎么样?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-01
    • 1970-01-01
    • 2011-10-24
    • 2013-03-20
    • 2014-06-07
    相关资源
    最近更新 更多