Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to put quotes around the URL string.
Passing a variable name without quotes if it's not defined.
✗ Incorrect
The URL initializer requires a string literal or variable of type String. The string must be quoted.
2fill in blank
mediumComplete the code to set the HTTP method to POST.
iOS Swift
var request = URLRequest(url: url)
request.httpMethod = [1] Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using lowercase method names without quotes.
Passing the method name without quotes.
✗ Incorrect
The httpMethod property expects a string with the HTTP method name in uppercase and quotes.
3fill in blank
hardFix the error in setting the Content-Type header for JSON.
iOS Swift
request.setValue([1], forHTTPHeaderField: "Content-Type")
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using unquoted strings.
Using wrong MIME types like application/xml.
✗ Incorrect
The Content-Type header value must be a string with the exact MIME type for JSON, quoted.
4fill in blank
hardFill both blanks to encode a dictionary as JSON data and assign it to the request body.
iOS Swift
let json: [String: Any] = ["name": "John", "age": 30] request.httpBody = try? JSONSerialization.[1](withJSONObject: json, options: .[2])
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using jsonObject instead of data method.
Passing invalid options.
✗ Incorrect
The method to convert JSON to Data is 'data', and 'prettyPrinted' is a valid option for formatting.
5fill in blank
hardFill all three blanks to create a URLSession data task that sends the request and handles the response.
iOS Swift
let task = URLSession.shared.dataTask(with: request) { data, response, error in guard let [1] = data, error == nil else { return } if let httpResponse = response as? [2], httpResponse.statusCode == [3] { print("Success") } } task.resume()
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using URLResponse instead of HTTPURLResponse for statusCode.
Using wrong status code numbers.
✗ Incorrect
The data is assigned to a variable (responseData), the response cast to HTTPURLResponse, and 200 is the success status code.