Back to search

Create a live blog app using Swift and Go

  • Neo Ighodaro
June 20th, 2018
You will need Xcode, Go, SQLite and Cocoapods installed on your machine. Some knowledge of Swift will be helpful.

Live blogs allow users to follow events live without audio or video. It's particularly useful when you are in situations where you cannot consume audio/video media. Live blogs have been used to cover things like football commentary, political commentary, and more.

In this article, we are going to consider how to build a live blogging application. We will be building it using Swift for iOS and we will use Go as the backend language for the application. When we are done with the application, this is what it will look like:

swift-liveblog-demo

Prerequisites

To get started you need the following:

  • Xcode (v9.x) running on your machine. Download Xcode.
  • Go (v0.10 or later) installed on your machine. Installation guide.
  • SQLite installed on your machine. Installation guide.
  • Knowledge of the Swift programming language.
  • Basic knowledge of the Go programming language.
  • Knowledge of using the Xcode IDE.
  • Cocoapods installed on your machine. Installation guide.

Let's get started.

Creating the Swift application

Launch Xcode and create a new 'Single View App' project. We will creatively name ours ... drum rolls ... LiveBlog. Next, close Xcode and cd to the root directory of your Xcode project and run the following command:

    $ pod init

This command will create a new Podfile in the root of your project. Open the Podfile in your code editor and paste the following code:

    platform :ios, '11.0'

    target 'LiveBlog' do
      use_frameworks!

      pod 'Alamofire', '~> 4.7.2'
      pod 'PusherSwift', '~> 6.1.0'
      pod 'PushNotifications', '~> 0.10.8'
      pod 'NotificationBannerSwift', '~> 1.6.3'
    end

Next, run the following command to install the packages listed above using Cocoapods:

    $ pod install

When the installation is complete, you will see a LiveBlog.xcworkspace file in the project directory. Open this file in Xcode.

Let's create our application's storyboard. Open the Main.storyboard file and what we want to do is create something similar to the board below:

swift-liveblog-storyboard

To create this, we added a new navigation controller and made it the entry point of the storyboard. We then assigned a reuse identifier to the cell on the table view controller called post. We also set the title of the view controller using the interface builder.

Next, create a table view controller called PostsTableViewController and set this as the custom class for the table view controller in the main storyboard.

In the PostsTableViewController paste in the following code:

    import UIKit
    import Alamofire
    import NotificationBannerSwift

    struct Post: Codable {
        let id: Int64
        let content: String
    }

    struct Posts: Codable {
        var items: [Post]
    }

    class PostsTableViewController: UITableViewController {

        var posts = Posts(items: [])

        override func viewDidLoad() {
            super.viewDidLoad()

            Alamofire.request("http://127.0.0.1:9000/posts").validate().responseJSON { resp in
                guard resp.result.isSuccess, let data = resp.data else {
                    return StatusBarNotificationBanner(title: "Unable to fetch posts", style: .danger).show()
                }

                if let posts = try? JSONDecoder().decode(Posts.self, from: data) {
                    self.posts = posts
                    self.tableView.reloadData()
                }
            }
        }

        override func numberOfSections(in tableView: UITableView) -> Int {
            return 1
        }

        override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return posts.items.count
        }

        override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "post", for: indexPath)
            let post = posts.items[indexPath.row]

            cell.textLabel?.text = post.content

            return cell
        }

    }

Above we have a two Codable structs for the Post and Posts objects. We will decode the response from the API to these objects and make working with JSON responses easier.

Recommended: Decoding JSON using Codable in Swift 4

In our viewDidLoad method, we make a request to the API to fetch the posts and then we save them to the posts property of the controller then we reload the tableView. The rest of the methods in the controller should be familiar to you. They are used to override the table view's rendering.

Adding realtime functionality

Because we are creating a live blog, we want to add the realtime functionality to the application so that when a new post is made, we get an instant update.

In the PostsTableViewController, import the Pusher Swift SDK:

    import PusherSwift

Now in the viewDidLoad method, we can add our Pusher functionality. At the top of the method after super.viewDidLoad(), add the following code:

    let pusher = Pusher(
        key: "PUSHER_APP_KEY", 
        options: PusherClientOptions(
            host: .cluster("PUSHER_APP_CLUSTER")
        )
    )

    let channel = pusher.subscribe("live-blog-stream")

    let _ = channel.bind(eventName: "new-post") { data in
        if let data = data as? [String: AnyObject] {
            if let id = data["id"] as? Int64, let content = data["content"] as? String {
                self.posts.items.insert(Post(id: id, content: content), at: 0)
                self.tableView.reloadData()
            }
        }
    }

Replace the PUSHER_APP_* keys with the value from your Pusher dashboard.

In the code above, we create an instance of the Pusher SDK and then we subscribe to the live-blog-stream channel. We then bind a callback to the new-post event on the channel.

Whenever this event is triggered, the callback is fired. In the callback, we update the posts with the new post that was passed with the event then we reload the tableView so the changes are reflected immediately.

With those few lines, we have implemented realtime functionality to the application. Easy right?

Creating the Go backend for our realtime application

The next thing we want to do is create the backend for our application. We will make it as simple as possible so we can easily demonstrate how to trigger events on a channel in Pusher using Go.

Create a new project directory for the Go application. Let's call it liveblog-backend and in that directory create a public directory:

    $ mkdir liveblog-backend
    $ cd liveblog-backend
    $ mkdir public

In the root directory, create a new file called main.go and in here is where all our Go code will reside.

Open the main.go file in your favorite editor and paste the following code into the file:

    package main

    import (
        "database/sql"
        "net/http"

        "github.com/labstack/echo"
        "github.com/labstack/echo/middleware"
        _ "github.com/mattn/go-sqlite3"
        pusher "github.com/pusher/pusher-http-go"
    )

    func main() {
        e := echo.New()

        e.Use(middleware.Logger())
        e.Use(middleware.Recover())

        db := initialiseDatabase("./storage.db")
        migrateDatabase(db)

        e.File("/admin", "public/admin.html")
        e.GET("/posts", getPosts(db))
        e.POST("/posts", savePost(db))

        e.Logger.Fatal(e.Start(":9000"))
    }

Above, we import the packages we will need for the Go application to function properly. We also defined a main function which will be the sole entry point of the application.

In the main function, we instantiated the Echo framework and we added some middlewares to the instance of echo.

Next, we initialized the database and ran a migration on the database. This will create a storage.db file in the root directory. This is the file SQLite will use to operate. Finally, we defined some routes for our application and specified the port we want our application to start on, 9000. In the main function, we referenced some functions we had not created so let's add these functions.

In the main.go file, add the following above the main function:

    func initialiseDatabase(filepath string) *sql.DB {
        db, err := sql.Open("sqlite3", filepath)

        if err != nil {
            panic(err)
        }

        if db == nil {
            panic("db nil")
        }

        return db
    }

    func migrateDatabase(db *sql.DB) {
        sql := `
            CREATE TABLE IF NOT EXISTS posts(
                    id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,
                    content TEXT
            );
    `
        _, err := db.Exec(sql)
        if err != nil {
            panic(err)
        }
    }

    func getPosts(db *sql.DB) echo.HandlerFunc {
        return func(c echo.Context) error {
            rows, err := db.Query("SELECT * FROM posts ORDER BY id DESC")
            if err != nil {
                panic(err)
            }

            defer rows.Close()

            result := PostCollection{}

            for rows.Next() {
                post := Post{}
                err2 := rows.Scan(&post.ID, &post.Content)
                if err2 != nil {
                    panic(err2)
                }

                result.Posts = append(result.Posts, post)
            }

            return c.JSON(http.StatusOK, result)
        }
    }

    func savePost(db *sql.DB) echo.HandlerFunc {
        return func(c echo.Context) error {
            postContent := c.FormValue("content")
            stmt, err := db.Prepare("INSERT INTO posts (content) VALUES(?)")
            if err != nil {
                panic(err)
            }

            defer stmt.Close()

            result, err := stmt.Exec(postContent)
            if err != nil {
                panic(err)
            }

            insertedID, err := result.LastInsertId()
            if err != nil {
                panic(err)
            }

            post := Post{
                ID:      insertedID,
                Content: postContent,
            }

            client.Trigger("live-blog-stream", "new-post", post)

            return c.JSON(http.StatusOK, post)
        }
    }

Above, we have four functions. The first is the initialiseDatabase function. We use this to create the database file if it does not exist and then create a connection to the database once it exists. The migrateDatabase function does just what the name suggests. It executes migrations for the database if it was not previously run.

The getPosts function gets the list of posts from the database and returns it as a JSON response. The savePost function saves a new post to the database and triggers an update to Pusher on the live-blog-stream channel.

The savePost function is referencing a Pusher client instance that does not exist so let's create that. In the main.go file right after the import statements, add the following:

    var client = pusher.Client{
        AppId:   "PUSHER_APP_ID",
        Key:     "PUSHER_APP_KEY",
        Secret:  "PUSHER_APP_SECRET",
        Cluster: "PUSHER_APP_CLUSTER",
        Secure:  true,
    }

Replace the PUSHER_APP_* keys with the keys from your Pusher application dashboard.

In the above, we instantiate the Pusher Go client with the credentials from the dashboard. This will make it possible to trigger events using the Pusher instance.

The final thing we want to do is add the object structures for our Post and PostCollection. In the same main.go file, add the following code below the Pusher instance above:

    // Post type
    type Post struct {
        ID      int64  `json:"id"`
        Content string `json:"content"`
    }

    // PostCollection type
    type PostCollection struct {
        Posts []Post `json:"items"`
    }

Now save and close the file.

Create a new admin.html file in the public directory and paste the following into it:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Admin Panel</title>
        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
        <style>
            .container {
                max-width: 500px;
            }
            .logo-space {
                text-align: center;
                padding: 50px 0;
                background-color: #bada55;
                margin: 10px 0;
            }
        </style>
    </head>
    <body>
        <div id="app">
            <div class="container">
                <div class="logo-space">
                    <h1>Live Blog</h1>
                </div>
                <div class="alert alert-success" role="alert" v-show="successfulPost">
                    Post added successfully!
                </div>
                <form action="/posts" method="POST" id="post-stuff" v-on:submit.prevent="submitForm">
                    <div class="form-group">
                        <textarea class="form-control" v-model="content" placeholder="Enter Post"></textarea>
                    </div>
                    <input type="submit" class="form-control btn btn-primary" name="submit" value="Update Stream">
                </form>
            </div>
        </div>
        <script src="https://cdn.jsdelivr.net/npm/vue@2.5.16/dist/vue.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.min.js"></script>
        <script>
            new Vue({
                el: "#app",
                data: {
                    content: "",
                    successfulPost: false
                },
                methods: {
                    submitForm() {
                        if (this.content.length > 0 && this.content !== "") {
                            let data = new FormData()
                            data.append("content", this.content)

                            axios.post("/posts", data).then(res => {
                                this.content = ""
                                this.successfulPost = true
                                setTimeout(() => this.successfulPost = false, 3000)
                            })
                        }
                    }
                }
            })
        </script>
    </body>
    </html>

The code above is for the admin page where we can add our new posts. This will then make a POST request to the API to add a new post to the database. When the post is added to the database, an event will be triggered by the Pusher Go client. This event will then be picked up by the Swift application and the iOS app will be updated in realtime.

Save the file and execute the following command to run our Go application:

    $ go run main.go

This will start a server on port 9000.

Testing our live blogging application

The next thing we need to do is test our application. Open your project in Xcode using the .xcworkspace file. Before building the application though, we need to do one last thing. Open the info.plist file and apply the following changes:

swift-liveblog-info-plist

With this change, you can build and run your application and it will talk directly with your local web application.

swift-liveblog-demo

Conclusion

In this article, we have seen how we can easily create a live blog using Swift, Go and Pusher Channels.

Pusher Channels makes it very easy to implement realtime features into almost any application in all languages. You should check out the documentation here to get started. The source code for this article is available on GitHub.

  • Channels

© 2018 Pusher Ltd. All rights reserved.

Pusher Limited is a company registered in England and Wales (No. 07489873) whose registered office is at 28 Scrutton Street, London EC2A 4RP.