Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

ios - How to show HTML text from API on the iPhone?

The best example to explain my situation is to use a blog post. Let's say I have a UITableView loaded with title's of blog posts that I got from an API. When I click on a row I want to show the detailed blog post.

When doing that, the API is handing back several fields, including the "post body" (which is HTML text). My question is, what should I use to display it so it shows up as formatted HTML? Should I use a UIWebView for that? I'm not sure if you use a UIWebView when you are literally viewing a web page (like initialize it with a URL or something) or if you can hand it an HTML string and it will format it properly.

There are several other fields that will be showing on this page, such as title, category, author, etc. I'm just using UILabels for those, so no problems there. But I don't know what to do with the HTML chunk. I'm doing all of this programmatically, btw.

If you can't tell, I'm relatively new to iOS development, only about 2-3 weeks in, with NO obj-c background. So if a UIWebView is the right approach, I'd also appreciate any "gotcha!" notes, if there are any.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As David Liu said, UIWebview is the way to go. I would recommend a few building the HTML string separately and then passing it to the UIWebView. Also, I'd make the background transparent, using [webView setBackgroundColor:[UIColor clearColor]] so that you have an easier time making things look as they should.

Here's a code sample:

- (void) createWebViewWithHTML{
    //create the string
    NSMutableString *html = [NSMutableString stringWithString: @"<html><head><title></title></head><body style="background:transparent;">"];

    //continue building the string
    [html appendString:@"body content here"];
    [html appendString:@"</body></html>"];

    //instantiate the web view
    UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.frame];

    //make the background transparent
    [webView setBackgroundColor:[UIColor clearColor]];

    //pass the string to the webview
    [webView loadHTMLString:[html description] baseURL:nil];

    //add it to the subview
    [self.view addSubview:webView];

}

NOTE:

The benefit to using a 'NSMutableString' is that you can continue to build your string through an entire parsing operation and then pass it to the the 'UIWebView', whereas a 'NSString' cannot be changed once it is created.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...