这是我的HTML示例字符串。
"<!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\"><html><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"><meta http-equiv=\"Content-Style-Type\" content=\"text/css\"><title></title><meta name=\"Generator\" content=\"Cocoa HTML Writer\"><style type=\"text/css\">p.p1 {margin: 0.0px 0.0px 0.0px 0.0px; line-height: 40.0px; font: 33.2px '.SF UI Text'; color: #000000; -webkit-text-stroke: #000000}span.s1 {font-family: '.SFUIText'; font-weight: normal; font-style: normal; font-size: 33.19pt; font-kerning: none}</style></head><body><p class=\"p1\"><span class=\"s1\">123</span></p></body></html>"
这里有两个功能,可以将HTML转换为属性字符串再转换为HTML,以处理服务器大小。
HTML的属性字符串:
func attributeToHTML(_ attr: NSAttributedString) -> String {
var resultHtmlText = ""
do {
let r = NSRange(location: 0, length: (attr.length))
let att = [NSAttributedString.DocumentAttributeKey.documentType: NSAttributedString.DocumentType.html]
let d = try attr.data(from: r, documentAttributes: att)
if let h = String(data: d, encoding: .utf8) {
resultHtmlText = h
}
}
catch {
print("utterly failed to convert to html!!! \n>\(String(describing: attr))<\n")
}
return resultHtmlText
}
HTML归因于字符串:
func htmlToAttribute(_ string: String) -> NSAttributedString {
let htmlString = string
var result = NSAttributedString()
do {
let options = [NSAttributedString.DocumentReadingOptionKey.documentType: NSAttributedString.DocumentType.html]
let str = try NSAttributedString(data: htmlString.data(using: String.Encoding.unicode, allowLossyConversion: true)!, options: options, documentAttributes: nil)
result = attributedString
} catch {
print(error)
}
return result
}
当我将HTML字符串转换为属性字符串时,它会增加字体大小,并且可以完美地将属性字符串转换为HTML。
通过枚举对象,我也可以编辑字体大小,但是它的动态内容会响应任何类型的HTML字符串。所以这不是解决方案。
请提出如何处理UITextview中的HTML内容以在服务器中进行编辑和存储的方法。