Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to decode HTML string coming from server to iOS readable string

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 431
    Comment on it

    Hi Readers,

    Many time we will get HTML content in our API response which we need to load into our component like UILabel.  We can convert this HTML content into normal string or more specifically NSAttributed string which we can set into UILabel with the effect of HTML tags. Following code snippet is useful for that:

    func decodeEnt() -> String{
            let encodedData = htmlString.dataUsingEncoding(NSUTF8StringEncoding)!
            let attributedOptions : [String: AnyObject] = [
                NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding
            ]
            var attributedString:NSAttributedString?
            
            do{
                attributedString = try NSAttributedString(data: encodedData, options: attributedOptions, documentAttributes: nil)
            }catch{
                print(error)
            }
    
            
            return attributedString!.string
        }
    

    Here in this function you need to pass HTML string coming from server and you will get attributed string in return. There are different attribute used as attributedOptions.  Hope it helps.

    Thanks for reading.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: