Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a URL from a string.
iOS Swift
let url = URL(string: [1]) Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to put quotes around the URL string.
Passing a variable name instead of a string.
✗ Incorrect
The URL initializer requires a string literal with quotes. So the correct answer is a quoted string.
2fill in blank
mediumComplete the code to start a data task to download image data.
iOS Swift
URLSession.shared.dataTask(with: url!) { data, response, error in if let data = [1] { // Use data } }.resume()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Checking 'response' or 'error' instead of 'data'.
Forgetting to unwrap the optional data.
✗ Incorrect
The downloaded image data is in the 'data' variable, so we check if 'data' is not nil.
3fill in blank
hardFix the error in updating the UI image inside the data task.
iOS Swift
DispatchQueue.main.[1] {
imageView.image = UIImage(data: data)
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using sync which can cause deadlocks.
Updating UI on a background thread.
✗ Incorrect
UI updates must happen on the main thread asynchronously, so use DispatchQueue.main.async.
4fill in blank
hardFill both blanks to safely unwrap the URL and start the data task.
iOS Swift
guard let url = [1](string: [2]) else { return } URLSession.shared.dataTask(with: url).resume()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Putting the whole initializer in one blank.
Using wrong variable names.
✗ Incorrect
We unwrap the URL by calling URL(string: urlString). The first blank is the type 'URL', the second is the string variable 'urlString'.
5fill in blank
hardFill all three blanks to create a UIImage from data and assign it to imageView on the main thread.
iOS Swift
if let data = data { DispatchQueue.main.[1] { imageView.image = [2](data: [3]) } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using sync instead of async.
Forgetting to unwrap data.
Not creating UIImage correctly.
✗ Incorrect
We use DispatchQueue.main.async to update UI, create UIImage(data: data), and assign it to imageView.image.