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

How to show HTML text from API on the iPhone?


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.


   self.textLbl.attributedText = [[NSAttributedString alloc] initWithData:    [@"html-string" dataUsingEncoding:NSUnicodeStringEncoding]                                                                          options:@{     NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType                                                                                     } documentAttributes:nil error:nil];


NSString *strForWebView = [NSString stringWithFormat:@"<html> \n"      "<head> \n"      "<style type=\"text/css\"> \n"      "body {font-family: \"%@\"; font-size: %@; height: auto; }\n"      "</style> \n"      "</head> \n"      "<body>%@</body> \n"      "</html>", @"helvetica", [NSNumber numberWithInt:12], ParameterWhereYouStoreTextFromAPI]; [self.webview loadHTMLString:strForWebView baseURL:nil];

I'm using this code to even set the font for the webview text and passing my ivar 'ParameterWhereYouStoreTextFromAPI' where I'm storing text obtained from api.