0
0
iOS Swiftmobile~10 mins

Error handling for network calls in iOS Swift - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to declare a function that fetches data from a URL.

iOS Swift
func fetchData(from url: URL, completion: @escaping (Result<Data, Error>) -> Void) [1]
Drag options to blanks, or click blank then click option'
Aasync {
B-> Void {
Cthrows {
D{
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'throws' without marking the function as throwing.
Using 'async' without async context.
Adding '-> Void {' which is redundant here.
2fill in blank
medium

Complete the code to create a URLSession data task with error handling.

iOS Swift
let task = URLSession.shared.dataTask(with: url) { data, response, error in
    if let [1] = error {
        completion(.failure(error))
        return
    }
}
Drag options to blanks, or click blank then click option'
Aerror
Bdata
Cresponse
Durl
Attempts:
3 left
💡 Hint
Common Mistakes
Checking 'data' or 'response' instead of 'error'.
Not unwrapping the optional error properly.
3fill in blank
hard

Fix the error in the code to safely unwrap data and call completion with success.

iOS Swift
guard let [1] = data else {
    completion(.failure(NSError(domain: "", code: -1, userInfo: nil)))
    return
}
completion(.success(data))
Drag options to blanks, or click blank then click option'
Aerror
Bresponse
Cdata
Durl
Attempts:
3 left
💡 Hint
Common Mistakes
Unwrapping 'response' or 'error' instead of 'data'.
Passing the optional 'data' directly without unwrapping.
4fill in blank
hard

Fill both blanks to start the task and resume it.

iOS Swift
let task = URLSession.shared.dataTask(with: url) { data, response, error in
    // handle response
}
task[1][2]
Drag options to blanks, or click blank then click option'
A.
Bstart()
Cresume()
Dbegin()
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'start()' which does not exist.
Forgetting the dot before the method call.
5fill in blank
hard

Fill all three blanks to complete a function that fetches data and handles errors properly.

iOS Swift
func fetchData(from url: URL, completion: @escaping (Result<Data, Error>) -> Void) {
    let task = URLSession.shared.dataTask(with: url) { data, response, error in
        if let [1] = error {
            completion(.failure(error))
            return
        }
        guard let [2] = data else {
            completion(.failure(NSError(domain: "", code: -1, userInfo: nil)))
            return
        }
        completion(.success([3]))
    }
    task.resume()
}
Drag options to blanks, or click blank then click option'
Aerror
Bdata
Dresponse
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong variable names for unwrapping.
Passing optional 'data' without unwrapping.