2013-07-10 46 views
0

我必须创建一个UIWebview,将我从API获得的一些数据添加到本地的HTML文件中。这是我第一次这样做,我无法找到如何做到这一点。合并HTML文件到UIWebView

我的HTML文件看起来像:

<h1>%%%title%%%</h1> 
     <p class="date">%%%date%%%</p> 
     <a %%%hrefimage%%% class="link-diapo"> 
      <div class="image"> 
       <img src="%%%img%%%" alt="%%%title%%%"/> 
       %%%diapo%%% 
      </div> 
     </a> 
     <div id="content" style="font-size:%%%size%%%px;"> 
      <p>%%%chapo%%%</p> 
      <p>%%%html%%%</p> 
      <p class="source">%%%author%%%</p> 
     </div> 

和我的数据:

 "title": "My title", 
     "date": "2013-07-10", 
     "hour": "19h45", 
     "chapo": "blablabla", 
     "author": "Me", 
     "description": "html text" 
... 

有没有做到这一点很容易的方法?或者我必须在HTML文件中检测%%%?

Thx!

回答

1

如果你有你在一个NSString初始HTML,你可以使用stringByReplacingOccurrencesOfString:withString :,像

NSError *error; 
NSString *initialHTMLString = [NSString stringWithContentsOfFile:(your file path) encoding:NSUTF8StringEncoding error:&error]; 

//do something to get the data back from the api, I'll assume NSData w/ JSON formatting 
NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:nil]; 
NSString *titleString = [jsonDic objectForKey:@"title"]; 

NSString *HTMLStringWithTitleAdded = [initialHTMLString stringByReplacingOccurencesOfString:@"%%%title%%%" withString:titleString]; 

然后,您将需要重复类似的东西每个你得到回关键数据来自API。

1

您可以使用Mustache模板引擎将字典的值注入标记。

实际加载的标记串入UIWebView你会做类似如下:

NSURL * URL = [NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]] 
[self.webView loadHTMLString:markup baseURL:URL];