bruce1337
bruce1337

Reputation: 370

How do I save/display line breaks properly in a UIWebView for the iPhone?

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?

Upvotes: 4

Views: 3118

Answers (2)

Nikolai Ruhe
Nikolai Ruhe

Reputation: 81868

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 ".

Upvotes: 2

zpesk
zpesk

Reputation: 4353

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.

Upvotes: 0

Related Questions