简体   繁体   中英

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

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. 在此处输入图片说明

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

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
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM