iOS App Development iOS Swift Tutorial iOS8

How to build a Trivia App using Swift Programming Language

In this post we will learn how to build a Trivia App using Swift programming Language.

What we will cover

  • Creating a new project.
  • Grand Central Dispatcher
  • How to fetch data from web using Swift.
  • Tweet Functionality
  • Run in Simulator

Requirements Xcode6

Create a new project

  • Open Xcode
  • File > New Project > Single Page Application
  • ProductName : TriviaApp
  • Language : Swift
  • Device : Iphone
  • Next and save the project

images

images

Grand Central Dispatcher

GCD (Not greatest common divisor) is a technology built by apple for efficiently using the multi core processors on IOS and OS X for improving the performance of the app.

Apps tend to become unresponsive when we perform tasks which take a long time like fetching data from a web server in the main thread. Ideally the main thread should be for handling touch events and reacting to the users events in realtime.

GCD help by pushing the slow running tasks to a background job queue to be executed concurrently without blocking the main thread.

GCD provide abstraction over the thread pool interface and helps user in writing code easily without worrying much about the the concurrency model.

How to fetch data from web using Swift.

There are different ways of fetching the data from the web but in our case we will use NSURLSession.sharedSession() to have singleton object.

A singleton class returns the same instance no matter how many times an application requests it. A typical class permits callers to create as many instances of the class as they want, whereas with a singleton class, there can be only one instance of the class per process. A singleton object provides a global point of access to the resources of its class. Singletons are used in situations where this single point of control is desirable, such as with classes that offer some general service or resource.

Lets implement the randomFact() function which will return a random fact each time we call the function.

 func randomFact() {
        let baseURL = NSURL(string: "http://numbersapi.com/random/trivia")
        let downloadTask = session.downloadTaskWithURL(baseURL, completionHandler: { (location, response, error) -> Void in
            if(error == nil){
                let objectData = NSData(contentsOfURL: location)
                let tmpData :NSString = NSString(data: objectData, encoding: NSUTF8StringEncoding)

                dispatch_async(dispatch_get_main_queue(), { () -> Void in                    self.factText.text = tmpData
                    if (tmpData.length > 130){
                        self.tweetButtonLabel.hidden = true
                    } else {
                        self.tweetButtonLabel.hidden = false
                    }
                    self.activityIndicator.stopAnimating()
                    self.activityIndicator.hidden = true
                })
            } else {
                let alertViewController = UIAlertController(title: "Error", message: "Couldn't connect to network", preferredStyle: .Alert)
                let okButton = UIAlertAction(title: "OK", style: .Default, handler: nil)
                let cancelButton = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
                alertViewController.addAction(okButton)
                alertViewController.addAction(cancelButton)
                self.presentViewController(alertViewController, animated: true, completion: nil)
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    self.activityIndicator.stopAnimating()
                    self.activityIndicator.hidden = true
                })
            }

        })
        downloadTask.resume()
    }

These tasks are executed in the background

  • First we create a baseURL which point to the api which return a random fact
  • Using the session object(Shared) we create a downloadTask to fetch the data and pass a completionHandler that will be called when the data is ready to be used
  • CompletionHandler has the following semantics.
    (location: where the data is stored locally, response : response from the web call, error : in case there are any errors)
  • The first thing we look at is if there is any error, if not we continue using the data by passing it to NSData and eventually to NSString.

These tasks occur in the main thread.

  • Get the reference to the main queue and pass it to the dispatch_async queue
  • Execute necessary code in the main thread for updating the UIView.

Tweet Functionality

The tweet functionality is provided by the Social Framework introduce in IOS.
However to use this feature we need to add the Social.Framework to our app. Click on the target button on the left side bar of the xcode.

images

images

The Social framework (Social.framework) provides a simple interface for accessing the user’s social media accounts. This framework supplants the Twitter framework and adds support for other social accounts, including Facebook, Sina Weibo, and others. Apps can use this framework to post status updates and images to a user’s account. This framework works with the Accounts framework to provide a single sign-on model for the user and to ensure that access to the user’s account is approved.

func tweetButton() {
        if SLComposeViewController.isAvailableForServiceType(SLServiceTypeTwitter) {

            var tweetSheet = SLComposeViewController(forServiceType: SLServiceTypeTwitter)
            tweetSheet.setInitialText(factText.text + " #TriviaApp")
            self.presentViewController(tweetSheet, animated: true, completion: nil)
        } else {
            let alertViewController = UIAlertController(title: "Oops", message: "No Twitter Account connected on the device. Go to Settings > Twitter and add a twitter account", preferredStyle: .Alert)
            let okButton = UIAlertAction(title: "OK", style: .Default, handler: nil)
            let cancelButton = UIAlertAction(title: "Cancel", style: .Cancel, handler: nil)
            alertViewController.addAction(okButton)
            alertViewController.addAction(cancelButton)
            self.presentViewController(alertViewController, animated: true, completion: nil)

        }
    }

Clone and run the project

You can find the code on Github. Clone the project and run
https://github.com/sarchak/TriviaApp
images

I used Treehouse to get started with IOS8 and Swift. I strongly recommend to try it out if you want to get started with IOS8 and Swift. Here are the links Non Affiliate link and Affiliate link

About the author

Shrikar

Backend/Infrastructure Engineer by Day. iOS Developer for the rest of the time.

/* ]]> */