将html文件合并到UIWebView中

时间:2013-07-10 21:03:52

标签: ios file uiwebview

我必须通过将我从API中获取的一些数据添加到我在本地的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!

2 个答案:

答案 0 :(得分:1)

如果你的初始HTML在NSString中,你可以使用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 :(得分:1)

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

要将标记字符串实际加载到UIWebView中,您可以执行以下操作:

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