下面的代码很好地与以前的斯威夫特一起工作。这是字符串的扩展。
func stringByConvertingHTML() -> String {
let newString = replacingOccurrences(of: "\n", with: "<br>")
if let encodedData = newString.data(using: String.Encoding.utf8) {
let attributedOptions : [String: AnyObject] = [
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType as AnyObject,
NSCharacterEncodingDocumentAttribute: String.Encoding.utf8 as AnyObject
]
do {
let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil) //Crash here
return attributedString.string
} catch {
return self
}
}
return self
}但在斯威夫特3,它崩溃了,说
*由于“NSInvalidArgumentException”异常终止应用程序,原因:-_SwiftValue unsignedIntegerValue:未识别的选择器发送到实例0x6080002565f0‘
有人建议我该怎么做吗?
发布于 2016-09-22 16:45:03
我遇到了同样的问题:
let attributedOptions : [String: AnyObject] = [
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType as AnyObject,
NSCharacterEncodingDocumentAttribute: String.Encoding.utf8 as AnyObject
]在这里,类型检查的String.Encoding.utf8失败。使用NSNumber(value: String.Encoding.utf8.rawValue)
发布于 2016-11-04 10:53:02
在Swift3中,不再需要对AnyObject的强制转换,也不需要NSNumber。
let attrs: [String: Any] = [
NSDocumentTypeDocumentAttribute : NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue
]发布于 2017-04-13 07:08:21
这篇文章挽救了我的日子。迁移到Swift 3之后,String.Encoding.utf8到String.Encoding.utf8.rawValue的小更改修复了这里报告的陷阱。
原始线:
...
options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: String.Encoding.utf8],
...改为
options: [NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue],将.rawValue添加到末尾..。
https://stackoverflow.com/questions/39643394
复制相似问题