【发布时间】:2015-11-23 10:18:25
【问题描述】:
我只是解析了来自 web 服务的响应,从响应中我必须显示 UIWebview 中特定键的接收数据。 Uiwebview中必须显示的数据包含一些特殊的标签,比如,等等,请教怎么做?
【问题讨论】:
标签: javascript html ios swift uiwebview
我只是解析了来自 web 服务的响应,从响应中我必须显示 UIWebview 中特定键的接收数据。 Uiwebview中必须显示的数据包含一些特殊的标签,比如,等等,请教怎么做?
【问题讨论】:
标签: javascript html ios swift uiwebview
注1:
我们在html标签中没有强调标签:
http://www.w3schools.com/tags/
所以浏览器看不懂代码。但你可以用两种方式处理它。
给当前标签添加一些css。
强调{ 字体样式:斜体; }
将其替换为浏览器已知的标签
您可以在 UIWebView 中添加一些 CSS 代码并根据需要设置它们的格式。 HTML 标签是您从 Web 服务收到的标签。 baseURL 适用于图像或相对链接。例如,如果你有
<a href='pica.jpg'>mypic</a>
而baseurl是
http://example.com
最终的网址将是
http://example.com/pica.jpg
如果它在您的申请文件中,您可以使用:
func getBaseUrl() -> NSURL{
var pref = prefrences()
let dirPaths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory,.UserDomainMask, true)
let fileManager = NSFileManager.defaultManager()
let docsDir = dirPaths[0] as! String // Document folder of application
let url = NSURL(fileURLWithPath: docsDir, isDirectory: true)
return url!
}
这个函数从根目录返回一个目录。
let baseURL = NSURL(string: "http://thebasepath.com/files")
var htmlContentTemplate =
"<!DOCTYPE html >" +
"<html dir=\"ltr\" " +
" <head>" +
"<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">" +
" <meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />" +
" <style>" +
" emphasis{ font-style: italic; }" +
" </style>" +
" </head>" +
" <body dir=\"rtl\" >" +
" <div>%1$s</div>" +
"<script>\n" +
"window.onload= function()\n" +
"{\n" +
"// your javscript code can be here"
"}" +
"</script>" +
" </body>" +
"</html>";
var final = htmlContentTemplate.replace("%1$s", withString: "your html in body tag")
var data = final.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false);
webView.loadData(data, MIMEType: "text/html", textEncodingName: "UTF8", baseURL: baseURL)
要将替换功能添加到字符串数据类型添加以下代码。下面的代码可以添加到任何 swift 文件中。
extension String
{
func replace(target: String, withString: String) -> String
{
return self.stringByReplacingOccurrencesOfString(target, withString: withString, options: NSStringCompareOptions.LiteralSearch, range: nil)
}
}
【讨论】: