How do I decode HTML entities in Swift?

后端 未结 23 1889
一生所求
一生所求 2020-11-22 01:47

I am pulling a JSON file from a site and one of the strings received is:

The Weeknd ‘King Of The Fall&         


        
23条回答
  •  灰色年华
    2020-11-22 02:48

    This answer was last revised for Swift 5.2 and iOS 13.4 SDK.


    There's no straightforward way to do that, but you can use NSAttributedString magic to make this process as painless as possible (be warned that this method will strip all HTML tags as well).

    Remember to initialize NSAttributedString from main thread only. It uses WebKit to parse HTML underneath, thus the requirement.

    // This is a[0]["title"] in your case
    let encodedString = "The Weeknd ‘King Of The Fall’"
    
    guard let data = htmlEncodedString.data(using: .utf8) else {
        return
    }
    
    let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [
        .documentType: NSAttributedString.DocumentType.html,
        .characterEncoding: String.Encoding.utf8.rawValue
    ]
    
    guard let attributedString = try? NSAttributedString(data: data, options: options, documentAttributes: nil) else {
        return
    }
    
    // The Weeknd ‘King Of The Fall’
    let decodedString = attributedString.string
    
    extension String {
    
        init?(htmlEncodedString: String) {
    
            guard let data = htmlEncodedString.data(using: .utf8) else {
                return nil
            }
    
            let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [
                .documentType: NSAttributedString.DocumentType.html,
                .characterEncoding: String.Encoding.utf8.rawValue
            ]
    
            guard let attributedString = try? NSAttributedString(data: data, options: options, documentAttributes: nil) else {
                return nil
            }
    
            self.init(attributedString.string)
    
        }
    
    }
    
    let encodedString = "The Weeknd ‘King Of The Fall’"
    let decodedString = String(htmlEncodedString: encodedString)
    

提交回复
热议问题