0
0
iOS Swiftmobile~10 mins

URLSession basics 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 create a default URLSession instance.

iOS Swift
let session = URLSession.[1]
Drag options to blanks, or click blank then click option'
Adefault
Bshared
Cconfiguration
Dinit
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'default()' which does not exist
Trying to call 'init()' directly
2fill in blank
medium

Complete 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'
A"https://apple.com"
BURL(string: "https://apple.com")
CurlString
Dhttps://apple.com
Attempts:
3 left
💡 Hint
Common Mistakes
Passing a URL object instead of a string
Forgetting quotes around the URL string
3fill in blank
hard

Fix 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'
A.begin()
B.start()
C.resume()
D.run()
Attempts:
3 left
💡 Hint
Common Mistakes
Using .start() or .begin() which are not valid methods
Forgetting to call any method to start the task
4fill in blank
hard

Fill 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'
Aerror
Berr
Cfailure
Dexception
Attempts:
3 left
💡 Hint
Common Mistakes
Using different names for the parameter and the unwrapped variable
Using undefined variable names
5fill in blank
hard

Fill 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'
Adata
Bresponse
CString.Encoding.utf8
DString.Encoding.ascii
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'response' instead of 'data'
Using ASCII encoding which may not work for all data