NEW! Master Swift design patterns with my latest book! >>

< Previous: Parsing JSON: Loading data into SwiftyJSON   Next: Finishing touches: didFinishLaunchingWithOptions >

Rendering a petition: loadHTMLString

After all the JSON parsing, it's time for something easy: we need to create a detail view controller class so that it can draw the petition content in an attractive way.

The easiest way for rendering complex content from the web is nearly always to use a WKWebView, and we're going to use the same technique from project 4 to create DetailViewController that contains a web view.

Go to the File menu and choose New > File, then choose iOS > Source > Cocoa Touch Class. Click Next, name it “DetailViewController”, make it a subclass of “UIViewController”, then click Next and Create.

Replace all the DetailViewController code with this:

import UIKit
import WebKit

class DetailViewController: UIViewController {
    var webView: WKWebView!
    var detailItem: [String: String]!

    override func loadView() {
        webView = WKWebView()
        view = webView

    override func viewDidLoad() {

This is almost identical to the code from project 4, but you'll notice I've added a detailItem property that will contain our dictionary of petition data.

That was the easy bit. The hard bit is that we can't just drop the petition text into the web view, because it will probably look tiny. Instead, we need to wrap it in some HTML, which is a whole other language with its own rules and its own complexities.

Now, this series isn't called "Hacking with HTML," so I don't intend to go into much detail here. However, I will say that the HTML we're going to use tells iOS that the page fits mobile devices, and that we want the font size to be 150% of the standard font size. All that HTML will be combined with the body value from our dictionary, then sent to the web view.

Place this in viewDidLoad(), directly beneath the call to super.viewDidLoad():

guard detailItem != nil else { return }

if let body = detailItem["body"] {
    var html = "<html>"
    html += "<head>"
    html += "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">"
    html += "<style> body { font-size: 150%; } </style>"
    html += "</head>"
    html += "<body>"
    html += body
    html += "</body>"
    html += "</html>"
    webView.loadHTMLString(html, baseURL: nil)

There's a new Swift statement in there that is important: guard. This is used to create an "early return," which means you set your code up so that it exits immediately if critical data is missing. In our case, we don't want this code to run if detailItem isn't set, so guard will run return if detailItem is set to nil.

I've tried to make the HTML as clear as possible, but if you don't care for HTML don't worry about it. What matters is that there's a Swift string called html that contains everything needed to show the page, and that's passed in to the web view's loadHTMLString() method so that it gets loaded. This is different to the way we were loading HTML before, because we aren't using a website here, just some custom HTML.

That's it for the detail view controller, it really is that simple. However, we still need to connect it to the table view controller by implementing the didSelectRowAt method. Previously we used the instantiateViewController() method to load a view controller from Main.storyboard, but in this project DetailViewController isn’t in the storyboard – it’s just a free-floating class. This makes didSelectRowAt easier, because it can load the class directly rather than loading the user interface from a storyboard.

So, add this new method to your ViewController class now:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    let vc = DetailViewController()
    vc.detailItem = petitions[indexPath.row]
    navigationController?.pushViewController(vc, animated: true)

Go ahead and run the project now by pressing Cmd+R or clicking play, then tap on a row to see more detail about each petition. Some petitions don’t have detail text, but most do – try a few and see what you can find.

Upgrade to the premium experience

Get all 40 projects in PDF and ePub, plus exclusive content that will take your Swift learning to the next level – buy the Hacking with Swift book today!

< Previous: Parsing JSON: Loading data into SwiftyJSON   Next: Finishing touches: didFinishLaunchingWithOptions >
Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Practical iOS 11 Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Average rating: 5.0/5

Click here to visit the Hacking with Swift store >>