Swift App Tutorial: SwiftStocks (Part II)

SwiftStocks Tutorial Part 2

In the first chapter of this series, we designed a model, created a mockup, and started a swift project, ending up with the first viewController -the tableView- with some hardcoded stocks and values.

In this second post, we are going to explain:

  1. How to create a Swift project (Part I)
  2. How to hide the status bar (Part I)
  3. How to use UITableView in Swift (Part I)
  4. How to use tuples in Swift
  5. How to use switch in Swift
  6. How to use  singleton pattern in Swift (Part II)
  7. How to use web services in Swift (Part II)
  8. How to use the NSNotificationCenter in Swift (Part II)

STEP 1: A Swift Singleton for gathering stocks data

If you remember our app model, we have a Singleton class which is the responsible of getting the stock data from the Yahoo Finance API. This singleton (now named “StockManagerSingleton“) will communicate via web services with Yahoo API in order to provide our ViewControllers with the proper real time data to show.

App Sketch

So…How to implement a Singleton class in Swift? Let’s see it:

Let’s create a new swift class named “StockManagerSingleton” by doing File->New->File->Swift File->Create. Change the code for this one:

There are other ways to implement this pattern, you can see more here.

Now, let’s check if we can call the method “printTest” from our StocksTableViewController.swift class

Change the method “didSelectRowAtIndexPath” for this code:

Now build and launch the app. When you touch/click on a cell, the message “TEST OK :)” should appear in the output. That means that our Singleton is working. Note that in Swift, we don’t have to import manually other Swift classes within the same project.

STEP 2: Calling Yahoo Finance API in Swift. Sending a NSNotification in Swift

We know that our Singleton class is working. Now it is time to start implementing the web services methods in order to gather stock data from Yahoo F-API.

What kind of method would we need? We have a table with some stock symbols on our StocksTableViewController. We need to now the value of those symbols. So we need a method in our Singleton which, receiving some symbols, provide us the stock value of each one.

Lets paint a simple sketch of the process:

UpdateStocksProcess

 

The steps are:

  1. Our StocksTableViewController calls the singleton method “updateListOfSymbols”
  2. The singleton method, send a request to Yahoo Finance API and get a response.
  3. If the response is correct, our Singleton sends a NSNotification with the data in the userInfo
  4. Our tableView was listening to the NSNotification, so it receives the fresh data and updates itself.

I am going to post all the code once and then, explain it little by little. Change ALL the code in StockManagerSingleton.swift for this one:

So lets see how this works:

  • //1: The request for the Yahoo Finance API should have that structure. So we have to build a string in a similar way
  • //2: With the array of stock tuples, we are building a piece of the request. This one: (“AAPL”,”GOOG”,”FB”). And then, we complete the request of the comment 1.
  • //3: We define what to do when Yahoo answers our request inside a completionBlock or closure. First of all, we check for errors.
  • //4: If there are no errors, we parse the answer into a JSON NSDictionary. We have to check again for errors in the parse process.
  • //5: No error during the parsing? Then we can extract the data we want from the NSDictionary, and send a NSNotification with the proper userInfo. We need to register the StocksTableViewController as a listener of this notification, in order to display the received data into the tableView. But this is done in the viewController itself later. NOTE: We send the notification in the main thread, because we are going to update the UI!
  • //6: Without this line, no request is sent, so you should never forget it!

It seems that we have a Singleton Class, with a method that provide us with yahoo stocks information. Sounds good. Lets check how it works!

STEP 3: How to listen for a NSNotification in Swift, and then reloading our data

Go to StocksTableViewController.swift. We are going to do some changes here too. We need to call the singleton for the data, listen to the NSNotification, and process and display the new information.

We are going to reload the tableView, however we have no reference to it in our viewController. Lets make an outlet!

1. Open the storyboard, and show the Assistan Editor (View->Assistant Editor->Show).

2. Now, command+click from the tableView to our ViewController. Name the IBOutlet “tableView”

Swift App Tutorial SwitfStocks

DONE.

We are going to update the data of our table, so our Array “stocks” is going to be modified at every update. It cannot be declared as “let”, because it is not constant. Change it and declare it as “var” (it was at the beginning of our class):

We have to register to listen to NSNotifications. We are going to do this at the viewDidLoad method:

As you can see, we are calling here to a new method: updateStocks(). Implement it as follows:

Here we have some interesting code:

  • The first two lines are responsible of calling the Singleton class and passing to the method updateListOfSymbols our array of symbols.
  • The final part of the method, is a code block to repeat this method every 15 seconds. We want our app to automatically update the table of stocks every 15 seconds (if you put a lower time of seconds, yahoo API is going to send you error responses).

Okey, we have now a method which calls to update our data every 15 seconds. Our singleton will get in touch with Yahoo Finance and send us a notification, which we have already registered for…but…we have to implement the method that do something with that notification!. Here it is, paste this code:

Let’s see:

  • We extract a NSArray with some stock info from the notification
  • The we update our stocks array (which is the datasource for our table)
  • Finally, we reload the table and the user see the updated values

We are DONE! Build and launch! Any doubts, problems our improvements…I read you in the comments.

Swift App Tutorial SwitfStocks

 

We have covered with the part 1 and part 2 the following concepts:

  1. How to create a Swift project (Part I)
  2. How to hide the status bar (Part I)
  3. How to use UITableView in Swift (Part I)
  4. How to use tuples in Swift 
  5. How to use switch in Swift
  6. How to use  singleton pattern in Swift (Part II)
  7. How to use web services in Swift (Part II)
  8. How to use the NSNotificationCenter in Swift (Part II)

 

Here you have the code to download:

Hope you liked this tutorial.

Want more? We will cover soon how to implement the other 2 viewControllers: The search screen and the details screen. Stay tuned!

Swift App Tutorial SwitfStocks

 

Follow me: @marioeguiluz

 

About @marioeguiluz

iOS Freelancer, Entrepreneur and Mobile App Expert

Categories: All, Apps, Development, Tutorial

13 comments

  • Mel Malinowski

    As I learn Swift, and had to migrate my singleton database class to Swift, this was the first clear, working example I found of how to do this Swift-style. Mahalo from South Kohala, Hawai’i.

      • Mel Malinowski

        I have found that one of the major challenges in a programming language new to you is learning the correct patterns. The grammar, so to speak. If your grammar is incorrect, the code will not work.

        Often, the Apple documentation, while technically correct, fails to give you an example that shows the pattern in a working example that is not obscured by needless complexity. Then you see and understand. Get it working, and then move on.

        Thanks for sharing this with us.

  • Beth

    Mario, thank you so much for this example. As Mel said, it is great to learn some of the correct patterns to use rather than hack code together and hope for the best.

    A quick question however, I sometimes get an ‘EXC_BAD_ACCESS (code=2)’ error on the below line:

    var quotes:NSArray = ((jsonDict.objectForKey(“query”) as NSDictionary).objectForKey(“results”) as NSDictionary).objectForKey(“quote”) as NSArray

    Do you know why this could be? It appears to only happen when I am getting just one query result back. (I have added some extra logic so that if only one quote is saved I will do a YQL query of symbol = * rather than symbol IN (

    Thanks again for your time and putting this together for the community.

    • @marioeguiluz

      Hi Beth,
      You are right. It seems that Yahoo API, changes the structure of the response when there is only 1 result! I think they should maintain it in every scenario but this API is not supported so this kind of things happens! As I read you have already solved it 🙂

Leave a Reply to Preston Ramirez Cancel reply

Your email address will not be published. Required fields are marked *