ios - Cannot convert value of type NSAttributedString.DocumentAttributeKey to .DocumentReadingOptionKey -
i found string extension somewhere on internet allows me turn html code attributed string:
func html2attributedstring() -> nsattributedstring { return try! nsattributedstring(data: self.data(using: string.encoding.unicode, allowlossyconversion: true)!, options: [nsdocumenttypedocumentattribute: nshtmltextdocumenttype], documentattributes: nil) }
it worked fine in swift 3, swift 4, xcode complains:
cannot convert value of type 'nsattributedstring.documentattributekey' expected dictionary key type 'nsattributedstring.documentreadingoptionkey'
how fix this?
you need pass 1 of available nsattributedstring documenttype options:
hypertext markup language (html) document.
static let html: nsattributedstring.documenttype
plain text document.
static let plain: nsattributedstring.documenttype
rich text format document.
static let rtf: nsattributedstring.documenttype
rich text format attachments document.
static let rtfd: nsattributedstring.documenttype
in case need pass first 1 (html) nsattributedstring.documenttype.html
so extension updated swift 4 should this:
extension string { var html2attributedstring: nsattributedstring? { { return try nsattributedstring(data: data(utf8), options: [.documenttype: nsattributedstring.documenttype.html, .characterencoding: string.encoding.utf8.rawvalue], documentattributes: nil) } catch { print("error: ", error) return nil } } var html2string: string { return html2attributedstring?.string ?? "" } }
Comments
Post a Comment