0
0
iOS Swiftmobile~10 mins

GET request with async/await 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 URL object 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://api.example.com/data"
Bhttps://api.example.com/data
CURL("https://api.example.com/data")
DurlString
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to put the URL string in quotes.
Passing a variable name that is not defined.
2fill in blank
medium

Complete the code to perform an asynchronous GET request using URLSession.

iOS Swift
let (data, _) = try await URLSession.shared.[1](from: url)
Drag options to blanks, or click blank then click option'
AdownloadTask
BdataTask
Cpost
Ddata(from:)
Attempts:
3 left
💡 Hint
Common Mistakes
Using dataTask which is not async/await compatible.
Using downloadTask which downloads to a file.
3fill in blank
hard

Fix the error in the async function declaration for fetching data.

iOS Swift
func fetchData() async throws -> Data {
    let url = URL(string: "https://api.example.com/data")!
    let (data, _) = try await URLSession.shared.data(from: url)
    return [1]
}
Drag options to blanks, or click blank then click option'
Aurl
Bdata
Cself
Dresponse
Attempts:
3 left
💡 Hint
Common Mistakes
Returning the URL instead of data.
Returning the response object which is not declared.
4fill in blank
hard

Fill both blanks to decode JSON data into a Swift struct.

iOS Swift
let decoder = JSONDecoder()
let result = try decoder.[1](MyStruct.self, from: [2])
Drag options to blanks, or click blank then click option'
Adecode
Bdata
CjsonData
Dencode
Attempts:
3 left
💡 Hint
Common Mistakes
Using encode instead of decode.
Passing wrong variable instead of data.
5fill in blank
hard

Fill all three blanks to complete the async function that fetches and decodes JSON.

iOS Swift
func fetchAndDecode() async throws -> MyStruct {
    guard let url = URL(string: [1]) else { throw URLError(.badURL) }
    let ([2], _) = try await URLSession.shared.data(from: url)
    let decoder = JSONDecoder()
    return try decoder.decode([3].self, from: data)
}
Drag options to blanks, or click blank then click option'
A"https://api.example.com/data"
Bdata
CMyStruct
Durl
Attempts:
3 left
💡 Hint
Common Mistakes
Not quoting the URL string.
Using wrong variable names for data.
Passing wrong type to decode.