2013-08-01 68 views
1

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

  1. 达到从移动网站的报价(我做了一些小的移动网站)
  2. 我存储在移动网站在我的iPhone的文档文件夹本地
  3. 我生成一个JSON文件以保存报价的名称,路径和截止日期。我将此JSON存储在我的i​​Phone的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。

回答

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Ç ,你需要定义一个特定的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调用,而不是HTTP。 它的工作原理,但苹果不推荐它。

+0

好吧,我知道这一点。但我必须用javascript来做...我该怎么做? – lucgian84

+0

你对这个[link](https://github.com/marcuswestin/WebViewJavascriptBridge)有什么看法? – lucgian84

+0

更新了我的答案。 – Horst