Cannot convert value of type NSAttributedString.DocumentAttributeKey to .DocumentReadingOptionKey

前端 未结 8 1968
鱼传尺愫
鱼传尺愫 2020-12-09 07:18

I found this string extension somewhere on SO that allows me to turn html code into an attributed string:

func html2AttributedString() -> NSAttributedStri         


        
8条回答
  •  独厮守ぢ
    2020-12-09 08:09

    For HTML string, NSAttributedString.DocumentType.html is the correct option.

    Swift 4

    extension String {
    
        var utfData: Data? {
            return self.data(using: .utf8)
        }
    
        var htmlAttributedString: NSAttributedString? {
            guard let data = self.utfData else {
                return nil
            }
            do {
                return try NSAttributedString(data: data,
               options: [
                         NSAttributedString.documentType: NSAttributedString.DocumentType.html,
                         NSAttributedString.characterEncoding: String.Encoding.utf8.rawValue
                        ], documentAttributes: nil)
            } catch {
                print(error.localizedDescription)
                return nil
            }
        }
    }
    

提交回复
热议问题