DPS923 MAP523 Week 6 Notes
Thursday, February 6 - classroom lecture
Monday, February 10 - hands-on in the computer-lab
This week and next, we learn how to use the network.
Thursday plan
Plan for this week:
- Review the past interaction we had with the network
- Learn the new / established way
- Both one-of and a collection
Covered in class, and some of the same information about the new / established way to interact with a web API.
Covered in class, and some of the same information about sending data to a web API.
Code examples
The course’s GitHub repo has code examples for many topics and techniques. You can download a zip of the code repo, or clone it.
- W06a1FetchIntro
- W06a2WebApiMore
Monday plan
A short time, at the beginning of class, to show-and-tell the “add new” pattern.
Mostly, time to work on the programming assignment, and get help from a classmate or the professor if you need it.
Summary
Here’s a list of topics that we learned something about this week:
- The
Data(contentsOf:)
initializer is blocking, and it’s for fetch (HTTP GET) only, so it should NEVER be used in a real app
- The URL Loading System is the name of the collection of techniques and code assets that provide access to resources identified by URLs
- Loading is an async task, done on a background thread
- The key component is an
URLSession
object, a “container” which coordinates network tasks
- Each task is a
URLSessionDataTask
, which represents the lifetime of ONE specific network task
- A data task can be configured to send OR receive
- It expects and works with in-memory data structures
- The data structures are always defined by data model classes
- The data task - for fetch (HTTP GET) - needs a URL at a minimum
- The data task initializer needs a URL and a closure function (that will execute when the data task completes)
- Upon completion, the data task calls the closure function, with values for three parameters (data, response, error)
- Inside the closure function, we must do three tasks…
- The first task is to check for an error
- The second task is to ensure that the response is what we expect
- The third task is to unpack the data
- Assuming success, the unpacked data is saved (copied or assigned) to an in-memory object (and then used in whatever way you want)
- Often, we will update the user interface (UI)
- To update the UI, we must get a reference to the main thread, because the data task is running on a background thread
- After the statement that creates and configures a data task, the task does not execute - instead, we must add a statement that executes the task
- If we want to send data to the web API, we must modify our approach
- We use a
URLRequest
object, and configure it with all four things that it needs (URL, method, headers, body)
- Other minor changes are needed to prepare the data to be sent and handle the response