Open link on a text set to UILabel as attributed string. Attributed string is read from a json response

191 Views Asked by At

I am reading this json response in my tableview cell. I have set this to a UILabel and managed to show this as attributed sting to my label. My view is showing the text inside the tags as link but the click on link does not work. What i want is to open the browser on tap on these links.

{"Disclaimer":"I have read & accept the <a href=\"https:\/\/staging.rentalcover.com\/pds\/W80P-J8ZP-INS\" target=\"_blank\">Policy Terms<\/a>. I have read & accept the <a href=\"https:\/\/staging.rentalcover.com\/pds\/W80P-J8ZP-INS\">Policy Terms<\/a>. This policy is issued by RentalCover.com, AFSL No.490058 and underwritten by Assetinsure Pty Ltd."}

Below is my Code

var htmlResponse:String = obj.Disclaimer ?? ""
let myText = htmlResponse
lbl_Disclaimer.attributedText = self.stringFromHtml(string: myText)
lbl_Disclaimer.font = UIFont(name: "Poppins-Regular", size: 13)

// MARK:- HTML TO STRING
func stringFromHtml(string: String) -> NSAttributedString? {
    do {
        let data = string.data(using: String.Encoding.utf8, allowLossyConversion: true)
        if let d = data {
            let str = try NSAttributedString(data: d,
                                             options: [NSAttributedString.DocumentReadingOptionKey.documentType:  NSAttributedString.DocumentType.html],
                                             documentAttributes: nil)
            return str
        }
    } catch {
    }
    return nil
}

Image of how the text is showing in my app. enter image description here

I am getting the link for the text 'Policy Terms' in json response and want it to be clickable to open the link in a browser.

Thank you

1

There are 1 best solutions below

2
On

Use the UIWebView to achieve this. On UIlable you can assign AttributedText but there is no way to determine which specific word is tapped from the text. So, place a UIWebView and call loadHTMLString("<HTML>some string </HTML>") method. Implement the Delegate method StartLoadRequest.

Please use the following code:-

func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebView.NavigationType) -> Bool {
        guard let url = request.url else{
            return false
        }
        if "\(url)".contains("http"){
            UIApplication.shared.openURL(request.url!)
        }
        return false
    }