3

I am trying to decode html data to simple string but I get all html syntax along with I am using alamofire get method Link for html data http://laorotava.municipiointeligente.es/webservices/getNewsAndroid.php?type=audioguides1_es

Any help will be appreciated

I have tried all codes and extension on stack overflow but unable to get proper results

 let urlString = "http://laorotava.municipiointeligente.es/webservices/getNewsAndroid.php?type=audioguides1_es"
        Alamofire.request(urlString).response { response in
            if let data = response.data{
                let str = data.html2AttributedString
                print(str)
            }
        }

I get String in along with html syntax

I want this text

Te damos la bienvenida a La Orotava, el pueblo con mayor desnivel de España. Abarca desde las playas del Rincón, a nivel del mar, hasta los 3718 metros del pico Teide, el punto más alto de España, cuya última erupción fue en 1798. Se cree que el nombre Orotava deriva de la palabra Arautápala, con el que denominaban a este territorio los antiguos aborígenes guanches. Tras la conquista, fue declarada Villa por el rey Felipe IV en 1648. Te invitamos a recorrerlo a través de dos rutas diferentes: La Orotava Secreta o Ruta Azul y La Orotava Legendaria o Ruta Verde.Cada ruta dura aproximadamente una hora y media a paso normal y sus contenidos son diferentes. Si dispones de tiempo, te recomendamos que hagas las dos rutas por separado para disfrutar de rincones, leyendas y secretos que La Orotava te ofrece. A lo largo del recorrido encontrarás, incrustadas en el suelo, placas circulares de metal dorado. Cada placa indica el número de pista en el color de la ruta a la que pertenece. Cuando te encuentres frente a estas placas, pulsa el número de pista correspondiente. Si no dispones del tiempo suficiente, te recomendamos que elijas sólo una ruta. Pregunta al personal de la Oficina Municipal de Turismo, te atenderán encantados y te ayudarán a elegir una de ellas en función de tus intereses. También tienes a tu disposición folletos y otros materiales en la oficina para ayudarte en esta decisión. Ten en cuenta que La Orotava está llena de calles pendientes con subidas y bajadas muy pronunciadas. Si eliges la ruta de La Orotava Legendaria, o Ruta Verde, te encontrarás un recorrido con menos desnivel. Por otro lado, la Ruta de La Orotava Secreta o Ruta Azul ofrece a los más aventureros vistas panorámicas únicas desde las mayores alturas a las que llega la visita. Te recomendamos realizar las rutas en horario de oficina para que tengas la oportunidad de encontrar abiertos el mayor número de espacios posible. Las iglesias suelen estar abiertas en horario de culto. Recuerda que tienes a tu disposición un botón de pausa y otro de repetición de los últimos 10 segundos en el reproductor, para hacerte más cómodo el recorrido. Cualquiera de las dos rutas está llena de sorpresas y rincones maravillosos. Adelante, pulsa la ruta de tu elección y adentrémonos juntos en este paseo por La Orotava.

3 Answers3

4

Your answer is here

extension String{

    var htmlToAttributedString: NSAttributedString? {
        guard let data = data(using: .utf8) else { return NSAttributedString() }
        do {
            return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
        } catch {
            return NSAttributedString()
        }
    }

    var htmlToString: String {
        return htmlToAttributedString?.string ?? ""
    }
}

API Call

let urlString = "http://laorotava.municipiointeligente.es/webservices/getNewsAndroid.php?type=audioguides1_es"

        Alamofire.request(urlString, method: .get, parameters: nil).responseJSON { response in

                do {

                    if let jsonDict = try JSONSerialization.jsonObject(with: (response.data as Data?)!, options: []) as? [String:AnyObject]{

                        if let body = jsonDict["body"] as? String{
                            print(body.htmlToString) // Your output is Here
                        }
                    }

                } catch _ {
                    print("Exception!")
                }
        }

Output:

enter image description here

Nikunj Kumbhani
  • 3,758
  • 2
  • 26
  • 51
  • Thanx for your effort but giving crash in my end I am still figuring out ``` NSURLConnection finished with error - code -1002 ``` – Meet Ios Developer Jul 16 '19 at 07:04
  • @MeetIosDeveloper Refer to this https://stackoverflow.com/a/32506939/10150796 Because recently I write this code in my project and share it it's working fine you can also see the output here. – Nikunj Kumbhani Jul 16 '19 at 07:14
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/196512/discussion-between-nikunj-kumbhani-and-meet-ios-developer). – Nikunj Kumbhani Jul 16 '19 at 07:25
1

You need to create NSAttributedString from HTML string.

extension String {
    var htmlToAttributedString: NSAttributedString? {
        guard let data = data(using: .utf8) else { return NSAttributedString() }
        do {
            return try NSAttributedString(data: data, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding:String.Encoding.utf8.rawValue], documentAttributes: nil)
        } catch {
            return NSAttributedString()
        }
    }
    var htmlToString: String {
        return htmlToAttributedString?.string ?? ""
    }
}

Whenever you want to use HTML text:

textView.attributedText = htmlString.htmlToAttributedString

Hitesh Borse
  • 479
  • 2
  • 12
1

Use the Below Extension for Data & String

extension Data {
    var html2AttributedString: NSAttributedString? {
        do {
            return try NSAttributedString(data: self, options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
        } catch {
            print("error:", error)
            return  nil
        }
    }
    var html2String: String {
        return html2AttributedString?.string ?? ""
    }
}

extension String {
    var html2AttributedString: NSAttributedString? {
        return Data(utf8).html2AttributedString
    }
    var html2String: String {
        return html2AttributedString?.string ?? ""
    }
}

Implementation in your code should be Like this.

 let urlString = "http://laorotava.municipiointeligente.es/webservices/getNewsAndroid.php?type=audioguides1_es"
        Alamofire.request(urlString).response { response in
            if let data = response.data{
                let str:NSAttributedString = data.html2AttributedString //call the extension method here
                print(str)
            }
        }
Mantu
  • 1,017
  • 1
  • 10
  • 21