Transcript: 03. Your First Asynchronous App
Most of the projects in this course interact with the server. It's included in the course materials. Open the course materials folder and finder, and find the Course Server folder. Course Server is a Vapor server that you run in a terminal. So open terminal next to your find a window. First, you need to change directory to Course Server. In terminal, type CD space. Then drag the Course Server folder from finder into terminal and press return. Type LS, to list the files in Course Server. This package.swift file is what you'll run to start the server. Type swift run, return, to run the Swift package. This takes a few minutes to fetch all the dependencies and build the server. When you see this server starting message, check the connection by opening a browser window and load local host 8080/hello. You can stop the server by pressing Control + C. And restart it with Swift Run. Press the up arrow to get Swift Run back and then press return. Restarting is quick because you already downloaded everything. If you leave this server running for a while, it might stop serving data correctly. If an app doesn't work as you expect, stop and restart the Course Server. For the rest of this part of the course, you'll work on this simple ticker app. In this episode, you'll fetch a list of stock symbols from the Course Server. The live ticker button is disabled until you select the list item. In episode five, you'll make this live ticker screen show live stock prices. Well, apparently live prices. These are actually random numbers you'll download from the Course Server. In your browser, reload the server page to check it's still running. In the course materials, locate the Little John starter project. In the project navigator, open the views and model groups. Starter projects in this course have all the views, navigation and data model already set up, so you can concentrate on writing the concurrency code to make the app work. The views you'll be working on are outside the views group for quick access. Your work on this first app will just give you a feel for what asynchronous code looks like. Don't worry about understanding how it works. You'll learn all that in future episodes. In this episode, you'll work on the code that fetches the list of stock symbols from the server. Symbol list view will display this list, by calling a method in Little John model. In Little John model, locate available symbols. When this method completes, it returns an array of strings. For now, it returns an empty array so the compiler doesn't flag an error. The throws keyword is the usual warning that this method can throw errors, which it does in the guard statement. The method tries to create a URL from the server's Little John symbols end point. This fails if the server isn't connected, so it throws an error message. At the top of this file is a string extension that lets you throw strings instead of creating custom error types. This simple error handling lets you focus on the concurrency code. The async keyword indicates this function contains a suspension point, which you'll add now, just before the return statement. You saw this at the end of the previous episode, but this time you want to check the response too. Unlike the old data task with method, data from can throw errors. First, you'll await the completion of the async method, and this could throw errors. So then you check for thrown errors. This is a big advantage of using data from instead of data task. You can't forget to handle errors. Next, you need to verify the server response and return the fetch data. Replace the dummy return line with this code. This is pretty much what you would write in a data task with completion handler, except you wouldn't be able to throw any errors. Also, you're not writing a completion handler. You're effectively writing synchronous code that will execute when your asynchronous task returns. To check your new method compiles, press Command + B, not Command + R. Before you run the app, you need to update the SwiftUI view to use your new async method. Open symbol list view, scroll down and start adding this code. where the to-do is just before .padding .horizontal. If Xcode doesn't immediately complain, press Command + B to get the error message. Invalid conversion from async function to synchronous function. SwiftUI view modifiers like onAppear run code synchronously and you are trying to call your new asynchronous method in a nonconcurrent context. Fortunately, switch concurrency has a solution for this scenario, replace on appear with task. Remember the capital T task you used in the playground? It let you run asynchronous code in the playground's synchronous context. This task view modifier lets you call asynchronous functions in the SwiftUI views synchronous context. But now there's a new problem it doesn't throw, so you must handle any errors here. Wrap it in a do catch. If the warnings don't go away, press Command + B to get rid of them. Task do catch is a standard code block for calling an async throwing function from a SwiftUI view. You'll use it in episode five, too. Like onAppear, task runs when the view appears on screen. But if you've already fetched your symbols, you don't want it to run again, so add this line before the do catch block and tie up the catch loose end with this line. Scroll up to see what this last error message is. The views in this app are already set up to display an alert whenever last error message changes. Okay, now build and run in an iPhone simulator. And there's your list of stock symbols. Well done. How about testing whether symbol list view catches an error thrown by available symbols? Stop the app in Xcode. Use the app switcher to show terminal. Then press Control + C to stop the server and build and run the app again. There's the alert with the error message could not connect to the server. This isn't even one of the strings you wrote into available symbols. Data from throws it when it fails to connect to the server. In terminal, restart the server. Press the up arrow to get swift run back. Then press return. Wait for the server starting message, build and run again, and your list is back. Select the stock symbol and then tap live ticker. Not much to see here yet. You'll implement this view after the next episode.