I want to convert HTML Tag
to String
, I used enum
to find the content length of the String
, according to the length i need to do some operations.
My modal
class,
class PostViewModel {
var content: TextContent
enum TextContent {
case expanded(String)
case collapsed(String)
static func == (lhs: TextContent, rhs: TextContent) -> Bool {
switch lhs {
case .collapsed(let content):
if case collapsed(content) = rhs {
return true
}
return false
case .expanded(let content):
if case expanded(content) = rhs {
return true
}
return false
}
}
}
}
And i am calling this function in cellForItem(at index: Int)
,
func applyVerticalSizeConcernedRendering(fromViewModel viewModel: PostViewModel) {
switch viewModel.content {
case .collapsed(let content):
let str = content.html2String
print(str)
case .expanded(let content):
break
}
}
html2String
is extension
class of String
extension String {
var html2AttributedString: NSMutableAttributedString? {
guard let data = data(using: String.Encoding.utf8) else { return nil }
let attrs: [String: Any] = [
NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue
]
do {
let attrStr = try NSMutableAttributedString(data: data, options: attrs, documentAttributes: nil)
return attrStr
} catch let error as NSError {
print(error.localizedDescription)
return nil
}
}
var html2String: String {
return html2AttributedString?.string ?? ""
}
}
The problem is it's crashing while converting HTML tag to String
It's crashing here,
let attrStr = try NSMutableAttributedString(data: data, options: attrs, documentAttributes: nil)
And the String
is not empty
Below is the example HTML String
,
<strong>I want to test HTML Tags<br><\/strong>dsfhjdjf sjdfdj djfjdfj djkf dfjdhf <strong>adjf<br>asks <\/strong>djfdkf<br><strong>dfdjk dkfjdk <\/strong>dfjik iai <strong>adsfhj<\/strong>
This is working fine when i tried with hardcode value, but it's crashing only when i get the String
from the enum
The crash log is,
*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 0 beyond bounds for empty array'
Can anyone please help in this?
")` – Milan Nosáľ Sep 11 '17 at 14:30