Search code examples
iosswiftwkwebview

iOS : how to Display Accordion in WkWebView through HTML strings Swift


I need to display accordion in WKWebView from the html string coming from API response like this. enter image description here I already tried so many solutions in SO to do this but still not able to create it please share some some solution or code to display this as expected. I am sharing my code

let fullDesc = responseDict?["description_middle"]?.string ?? ""
                    let htmlString:String! = fullDesc //(postDict?["description"]!.stringValue ?? "")
                    
                    //self.detailWeb.customUserAgent = "Mozilla/5.0 (Windows NT 10.0) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/42.0.2311.135 Safari/537.36 Edge/12.10136"

                    
                    self.detailWeb.loadHTMLString("<html><body><style>p{align-items:justify;justify-content:justify} h1, h2, h3, h4, h5, h6{font-size:20px; font-weight:bold;} </style><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0,Proxima Nova-Regular\">\(htmlString!)</body></html>", baseURL: nil)
                

And here is the html string i got from the response

"description_middle": "{\"ac_title\":[\"When Should I take this Service?\",\"What benefits will I get by taking this onsite styling consultation service?\",\"Can I select a Fashion Stylist of my choice for this consultation?\",\"What Happens after I make the Payment?\"],\"ac_description\":[\"<p>You should take this Wardrobe Consultation Service if you are facing any of the following situations:<\\/p>\\r\\n\\r\\n<ul>\\r\\n\\t<li>You are struggling to find clothes that fit and flatter your body type<\\/li>\\r\\n\\t<li>You have a big event coming up and need help putting together the perfect outfit<\\/li>\\r\\n\\t<li>you want to update your professional image and make a great first impression<\\/li>\\r\\n\\t<li>you have a closet full of clothes but nothing to wear<\\/li>\\r\\n\\t<li>you want to build a sustainable wardrobe that is both stylish and environmentally friendly<\\/li>\\r\\n<\\/ul>\\r\\n\",\"<p>Taking a Wardrobe Consultation Service brings you several benefits. Some of those benefits are given below:<\\/p>\\r\\n\\r\\n<ul>\\r\\n\\t<li>Time and Convenience:&nbsp;A personal stylist saves your time and effort by doing the shopping, research and curating outfits for you, freeing up your own time to focus on other things.<\\/li>\\r\\n\\t<li>Increased Confidence:&nbsp;A stylist can help you develop your personal style, which can lead to increased confidence in your appearance and self-esteem.<\\/li>\\r\\n\\t<li>Expertise:&nbsp;Personal stylists have expertise in fashion, body shapes, color analysis and current trends, allowing you to benefit from their professional knowledge and advice.<\\/li>\\r\\n\\t<li>Maximizing Wardrobe:&nbsp;A stylist can help you to get the most out of your existing wardrobe, by creating new outfits and suggesting key pieces to purchase, making the most of your investment.<\\/li>\\r\\n\\t<li>Cost Savings:&nbsp;By investing in a personal stylist, you may save money in the long run by avoiding costly fashion mistakes, and making informed purchases that add value to your wardrobe.<\\/li>\\r\\n<\\/ul>\\r\\n\",\"<p>We would be introducing this feature in future. Until then, StyleBuddy will assign you the best available stylist at the time of your booking.<\\/p>\\r\\n\",\"<p>Our Client Support Team will reach out to you to initiate your service sessions. You will be asked to update a Client Information Form, which is required for the Stylist to prepare for your Service. You can also call or WhatsAPP us on&nbsp;+91-00&nbsp;to enquire about&nbsp;your appointment. This service is available from 10 AM to 7 PM India time except on Sundays.<\\/p>\\r\\n\"]}"

Solution

  • As per my understanding you have parsed the response and want to show the response in the form of an Accordion. This can be easily done with <details> and <summary> tags.

    Here is a code for reference:

    import UIKit
    import WebKit
    
    // Hardcoded response as a dictionary
    let descriptionMiddle: [String: Any] = [
        "ac_title": [
            "When Should I take this Service?",
            "What benefits will I get by taking this onsite styling consultation service?",
            "Can I select a Fashion Stylist of my choice for this consultation?",
            "What Happens after I make the Payment?"
        ],
        "ac_description": [
            "<p>You should take this Wardrobe Consultation Service if you are facing any of the following situations:</p>\r\n\r\n<ul>\r\n\t<li>You are struggling to find clothes that fit and flatter your body type</li>\r\n\t<li>You have a big event coming up and need help putting together the perfect outfit</li>\r\n\t<li>you want to update your professional image and make a great first impression</li>\r\n\t<li>you have a closet full of clothes but nothing to wear</li>\r\n\t<li>you want to build a sustainable wardrobe that is both stylish and environmentally friendly</li>\r\n</ul>\r\n",
            "<p>Taking a Wardrobe Consultation Service brings you several benefits. Some of those benefits are given below:</p>\r\n\r\n<ul>\r\n\t<li>Time and Convenience:&nbsp;A personal stylist saves your time and effort by doing the shopping, research and curating outfits for you, freeing up your own time to focus on other things.</li>\r\n\t<li>Increased Confidence:&nbsp;A stylist can help you develop your personal style, which can lead to increased confidence in your appearance and self-esteem.</li>\r\n\t<li>Expertise:&nbsp;Personal stylists have expertise in fashion, body shapes, color analysis and current trends, allowing you to benefit from their professional knowledge and advice.</li>\r\n\t<li>Maximizing Wardrobe:&nbsp;A stylist can help you to get the most out of your existing wardrobe, by creating new outfits and suggesting key pieces to purchase, making the most of your investment.</li>\r\n\t<li>Cost Savings:&nbsp;By investing in a personal stylist, you may save money in the long run by avoiding costly fashion mistakes, and making informed purchases that add value to your wardrobe.</li>\r\n</ul>\r\n",
            "<p>We would be introducing this feature in the future. Until then, StyleBuddy will assign you the best available stylist at the time of your booking.</p>\r\n",
            "<p>Our Client Support Team will reach out to you to initiate your service sessions. You will be asked to update a Client Information Form, which is required for the Stylist to prepare for your Service. You can also call or WhatsApp us on&nbsp;+91-00&nbsp;to inquire about&nbsp;your appointment. This service is available from 10 AM to 7 PM India time except on Sundays.</p>\r\n"
        ]
    ]
    
    
    class ViewController: UIViewController, WKNavigationDelegate {
        private var webView: WKWebView!
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // Create a WKWebView instance
            webView = WKWebView(frame: view.bounds)
            webView.navigationDelegate = self
            view.addSubview(webView)
    
            // Load the HTML content
            loadAccordionHTML()
        }
    
        private func loadAccordionHTML() {
            let titles = descriptionMiddle["ac_title"] as? [String] ?? []
            let descriptions = descriptionMiddle["ac_description"] as? [String] ?? []
            
            var accordion = ""
            for i in 1..<titles.count {
                accordion += """
                <details>
                  <summary>\(titles[i])</summary>
                  <p>\(descriptions[i])</p>
                </details>
                """
            }
            
            // Please update / stylize the html content as needed.
            let htmlString = "<div> \(accordion) </div>"
            webView.loadHTMLString(htmlString, baseURL: nil)
        }
    }
    
    

    Additional references: