如何将包含双引号的HTML字符串加载到UIWebView中

3

我是一个HTML字符串,看起来像这样:

<html> <head> <title>some text</title> <link rel="stylesheet" href="http://www.xyz.com/css/main.mobile.css" /> ...

文本本身包含双引号,那么我该如何加载到NSString中呢?因为我不能这样做:

 NSString *html = @"  "

"请将上述HTML字符串放入双引号中。我的目标是将该HTML字符串加载到UIWebView中。提前感谢您的帮助。"
4个回答

2

如果您正在使用字符串文字,则只需使用反斜杠转义双引号,像这样:

NSString *html = @"<html> <head> <title>some text</title> <link rel=\"stylesheet\" ...";

1

你可以在每个引号前面加上反斜杠

NSString *test = @"lorem\"ipsum\"do...";

或者将HTML放在一个单独的文件中,并将其加载到NSString中。
// get a reference to our file
NSString *myPath = [[NSBundle mainBundle]pathForResource:@"myfile" ofType:@"html"];

// read the contents into a string
NSString *myFile = [[NSString alloc]initWithContentsOfFile:myPath encoding:NSUTF8StringEncoding error:nil];

// display our file
NSLog("Our file contains this: %@", myFile);

0
htmlStr = [htmlStr stringByReplacingOccurrencesOfString:@"\"" withString:@"\\\""];

然后加载到WebView中

[self.webView loadHTMLString:htmlStr baseURL:nil];

0

另一种方法是将字符串中的所有双引号替换为单引号。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接