Tutorial details

Swifting with BaasBox | App Code for Sale | Preview

Swifting with BaasBox - Part 1 | Building a quiz app with BaasBox | iOS Tutorial

Swifting with BaasBox Part 1 | Building a quiz app with BaasBox

Overview PAGE TOP

Unless you have been living under a stone you are probably aware that Apple has released Swift, a new programming language to develop iOS and Mac OS X.

Even if you are a seasoned Objective-C developer, you will find that the language is completely different and to some extent disruptive. The syntax looks very similar to a scripting language, but the semantics is as complex as the one of Objective-C.

The good news is that Swift does not substitute Objective-C, it's a new alternative and you can reuse all your existing Objective-C code in Swift.

In this series we are going to build QuizWorldCup, a simple quiz application that allows users to answer questions about the World Cup. The application features:

  • login/signup: a user can create an account or use an existing one
  • game: the actual game, where the users is asked questions and given four alternatives to pick from
  • rankings: the list of users scores.
  • settings: a panel to allow the user customizing the application, for example, by setting an avatar
  • a back end to collect user profiles, questions and ranking

Here is a screenshot of the final application we are going to build.

Quiz App 2014 World Cup | Preview

In this first part we are going to set up the first view, which allows the user to login or signup. Data will be stored on BaasBox, an open source back end, which comes with an iOS SDK developed in Objective-C. You will see how it is easy to call Objective-C code in Swift. Without further ado, let's get started.

Note: as of today, we are not allowed to post screenshots of Xcode 6.

Requirements PAGE TOP

These are the requirements to complete this tutorial:

Setting up BaasBox PAGE TOP

Installing BaasBox is a breeze. Just follow these simple instructions. After you are done point your browser to http://localhost:9000 and check if you see the home view of BaasBox. That's really all you need to do to get started!

Building the Home Screen PAGE TOP

Open Xcode, create a new project using the "Single View application" template, select Swift as the programming language and name it "QuizWorldCup".

Now open the storyboard, select the only view controller and then "Editor -> Embed In -> Navigation Controller". This will create create the "shell" of the application, which is built on top of the good old UINavigationController class.

Next create a new Swift class named "HomeViewController" that extends UIViewController. This is gonna be the first view of the application. When the user is logged in it will show options like "Play" or "Rankings", otherwise it will prompt the login view. Add a label to the view controller, then select the view controller in the storyboard and set its class to "HomeViewController".

Finally, using the Assistant Editor, create an IBOutlet to link the label. At this point your class should be like this.

import UIKit

class HomeViewController: UIViewController {

    @IBOutlet var statusLabel: UILabel

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

    }

}

The next step is to import and set up the BaasBox SDK

Importing BaasBox PAGE TOP

Download the BaasBox SDK from Github, open the 'BaasBox-iOS-SDK' folder, select all the files and drop them on Xcode. Make sure you are copying items into the project. Xcode will ask you to create a "bridging header", which is needed to link Objective-C code to Swift. Click "Yes" and you will end up with a file named "QuizWorldCup-Bridging-Header.h".

Note: do NOT drag the whole "BaasBox-iOS-SDK" folder on the Xcode project, otherwise you won't be asked to create a bridging header. This is probably a bug in Xcode 6 and will be fixed in future releases. The next step is to create the login view controller.

Open "QuizWorldCup-Bridging-Header.h" and add

#import "BAAClient.h"

Now open "AppDelegate.swift" and modify didFinishLaunchingWithOptions as follows

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {

    BaasBox.setBaseURL("http://localhost:9000", appCode: "1234567890")

    return true

}

This is the only configuration needed for the BaasBox SDK. Appcode is a special code that identifies your application. By default it's "1234567890".

Next, open "HomeViewController.swift" and add the following method

override func viewWillAppear(animated: Bool)  {

    super.viewWillAppear(animated)

    let client = BAAClient.sharedClient()

    if client.isAuthenticated() {

        statusLabel.text = "Logged in"

    } else {

        statusLabel.text = "Not logged in"

        self.navigationController.performSegueWithIdentifier("showLogin", sender: nil)

    }      

}

This code will detect whether the user is logged in or not. In the first case, it will show the login view, otherwise it will just show the "Logged in" label.

Creating the Login View PAGE TOP

Open the storyboard and drop a new view controller in the scene. Then control-click on the navigation controller and drag a line onto the new view controller. When you release select "show detail" from the pop up menu. Now select the newly created segue and in the attributes inspector name it "showLogin".
Create a new Swift class and name it "LoginViewController". Now select the last view controller created in the storyboard and assign it the class "LoginViewController" that you have created. Next, still in the storyboard, populate the login view controller with the following components:

  • two text fields, one for the username and one for the password
  • a button labelled "Signup"
  • a button labelled "Login"
  • a label to show error messages
  • an activity indicator to show an ongoing activity

Now use the assistant editor control-drag from each component and create an IBOutlet. After this, the code should look like this.

import UIKit

class LoginViewController: UIViewController {

    @IBOutlet var usernameField: UITextField

    @IBOutlet var passwordField: UITextField

    @IBOutlet var loginButton: UIButton

    @IBOutlet var signupButton: UIButton

    @IBOutlet var spinner: UIActivityIndicatorView

    @IBOutlet var errorLabel: UILabel



    init(coder aDecoder: NSCoder!)  {

        super.init(coder: aDecoder)

    }



    init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {

        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)

    }



    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

    }

}

Next override the viewDidLoad function as follows

override func viewDidLoad() {

    super.viewDidLoad()

    usernameField.placeholder = "Username"

    passwordField.placeholder = "Password"

    spinner.hidesWhenStopped = true

    errorLabel.text = ""

}

Here we are simply setting the placeholders for the text fields, configuring the activity indicator and cleaning the error label.
Finally, still using the assistant editor, control-drag from the buttons again on the "LoginViewController" class but this time create two IBActions to trigger the signup and login operations. This is the complete code for the class.

import UIKit



class LoginViewController: UIViewController {

    @IBOutlet var usernameField: UITextField

    @IBOutlet var passwordField: UITextField

    @IBOutlet var loginButton: UIButton

    @IBOutlet var signupButton: UIButton

    @IBOutlet var spinner: UIActivityIndicatorView

    @IBOutlet var errorLabel: UILabel

    let client = BAAClient.sharedClient()



    init(coder aDecoder: NSCoder!)  {

        super.init(coder: aDecoder)

    }



    init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {

        super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)

    }



    override func viewDidLoad() {

        super.viewDidLoad(

        usernameField.placeholder = "Username"

        passwordField.placeholder = "Password"

        spinner.hidesWhenStopped = true

        errorLabel.text = ""

    }



    // Actions



    @IBAction func loginTapped(sender: UIButton) {

        loginButton.enabled = false

        signupButton.enabled = false

        spinner.startAnimating()

        client.authenticateUser(usernameField.text, password:passwordField.text, { (success: Bool, error: NSError!) -> () in

            self.spinner.stopAnimating()

            self.loginButton.enabled = true

            self.signupButton.enabled = true

            if (success) {

                println("logged")

               self.dismissModalViewControllerAnimated(true, completion: nil)

            } else {

                self.errorLabel.text = error.localizedDescription

            }

            })

    }



    @IBAction func signupTapped(sender: UIButton) {

        loginButton.enabled = false

        signupButton.enabled = false

        spinner.startAnimating()

        client.createUserWithUsername(usernameField.text, password:passwordField.text, completion: { (success: Bool, error: NSError!) -> () in



            self.loginButton.enabled = true

            self.signupButton.enabled = true

            self.spinner.stopAnimating()



            if (success) {

                println("created")

                self.usernameField.resignFirstResponder()

                self.passwordField.resignFirstResponder()

                self.dismissModalViewControllerAnimated(true, completion: nil)



            } else {

                self.errorLabel.text = error.localizedDescription

            }

            })

    }



    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

    }



}

During either login or signup we show the activity indicator and disable the buttons. When we get a response we check the result in a closure and according to the content we show either an error message or we go back to the HomeViewController. Notice that in both cases (login and signup) the BaasBox SDK stores locally the authentication token that is needed for future authenticated calls. Now it's time to test the application!

Assuming the BaasBox server is still running locally, build, run and signup. If everything is okay you will see a "Logged in" message in the Home view controller. If you restart the application you will see that the login screen is not prompted anymore, because authentication data is already stored. Now you can reset the simulator and test the login using the same credentials. Finally, you can reset again the simulator and enter wrong credentials to check if the error message is correctly displayed.

Conclusion PAGE TOP

This is the end of the first part of this series. You have learned how to configure an Xcode project with BaasBox and how you can use its Objective-C SDK to signup or login using Swift. In the next part we will finish the home view controller and we will build the real game that loads questions from the backend and stores the results for each user. In the meantime, enjoy swifting!

0 Comments Leave a comment

Please login in order to leave a comment.

Newest first
!

Sign-in to your Chupamobile Account.

The Easiest way to Launch your next App or Game.

Join Chupamobile and get instant access to thousands of ready made App and Game Templates.

Creating an account means you’re okay with Chupamobile’s Terms of Service and Privacy Policy.