views:

303

answers:

2

I have a UIWebView-based iPhone application that reads in HTML from a SQLite database. The user can save new information, entered via a UITextView that accepts carriage returns. How do I display these carriage returns (line breaks) properly in the UIWebView? I have tried using something like this:

NSString *HTMLData = [mySQLiteDataObject text]; 
HTMLData = [HTMLData stringByReplacingOccurrencesOfString:@"\\n"
  withString:@"<br>"];  
[webView loadHTMLString:HTMLData baseURL:nil];

But it doesn't look like the text is recognized as having line breaks: the text is displayed in one continuous line in the webView. When I print out the text in the console, it comes through with the line breaks intact.

I've tried using \n, \r and \r\n in the example code above, with no success. Am I saving the user's text incorrectly, or doing the wrong thing on the display side?

A: 

If i am not mistaken, when you replace "\\n" with an HTML break tag it should look like this:

 HTMLData = [HTMLData stringByReplacingOccurrencesOfString:@"\\n"
  withString:@"<br />"];

It seems you were missing the forward slash in the break statement.

zPesk
+2  A: 

I can see two back slashes in your search string: You have to replace "\n", not "\\n" to make it work.

But you really want to sanitize your input before loading it into the UIWebView. At least you have to mask <, >, &, and ".

Nikolai Ruhe
Yep, the extra backslash was the culprit. I could have sworn I saw the double backslashes recommended somewhere else. For more background on sanitizing, take a look at this general conceptual explanation:http://experimentgarden.blogspot.com/2009/07/how-to-stop-hacker-dont-trust-user.htmlI wound up writing a basic sanitizeForDisplay method that extends NSString.
tinymagic