Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a default URLSession instance.
iOS Swift
let session = URLSession.[1] Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'default()' which does not exist
Trying to call 'init()' directly
✗ Incorrect
The shared property gives you a shared singleton URLSession instance for simple tasks.
2fill in blank
mediumComplete the code to create a URL from a string.
iOS Swift
guard let url = URL(string: [1]) else { return }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Passing a URL object instead of a string
Forgetting quotes around the URL string
✗ Incorrect
The URL(string:) initializer expects a string literal or variable containing the URL string.
3fill in blank
hardFix the error in the code to start a data task.
iOS Swift
let task = session.dataTask(with: url) [1]
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using .start() or .begin() which are not valid methods
Forgetting to call any method to start the task
✗ Incorrect
You must call resume() on the task to start it. Other methods do not exist.
4fill in blank
hardFill both blanks to handle the data and error in the completion handler.
iOS Swift
let task = session.dataTask(with: url) { data, response, [1] in if let error = [2] { print(error.localizedDescription) } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for the parameter and the unwrapped variable
Using undefined variable names
✗ Incorrect
The completion handler parameter for errors is usually named error. You check it with if let error = error.
5fill in blank
hardFill all three blanks to safely unwrap data and convert it to a string.
iOS Swift
let task = session.dataTask(with: url) { data, response, error in guard let [1] = data, error == nil else { return } let result = String(data: [2], encoding: [3]) print(result ?? "No data") }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'response' instead of 'data'
Using ASCII encoding which may not work for all data
✗ Incorrect
You unwrap data safely, then use it to create a string with UTF-8 encoding.