Friday, February 10, 2017

How to Decode a String Except Html Tags Using Swift Language

No comments :

1.Create a Header Class Name as Helper.Swift
//  Helper.swift


static func toString(_ parameter: Any?, defaultValue: String = "") -> String
    {
        if let stringValue = parameter as? String {
            let decodedString = String(htmlEncodedString: stringValue)
            return decodedString
        }
        return defaultValue
    }



//Extension For Html Decode

extension String
{
    init(htmlEncodedString: String)
    {
        self.init()
        guard let encodedData = htmlEncodedString.data(using: .utf8) else {
            self = htmlEncodedString
            return
        }
        
        let attributedOptions: [String : Any] = [
            NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
            NSCharacterEncodingDocumentAttribute: String.Encoding.utf8.rawValue
        ]
        do {
            let attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
            self = attributedString.string
        } catch {
            print("Error: \(error)")
            self = htmlEncodedString
        }
    }

}


Usage : 
        self.msg = Helper.toString(dictionary["msg"] as Any)

No comments :

Post a Comment