0
0
iOS Swiftmobile~10 mins

POST request with JSON body 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"
BURL(string: "https://api.example.com/data")
Chttps://api.example.com/data
DurlString
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.
2fill in blank
medium

Complete 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'
A"POST"
B"GET"
CPOST
Dpost
Attempts:
3 left
💡 Hint
Common Mistakes
Using lowercase method names without quotes.
Passing the method name without quotes.
3fill in blank
hard

Fix 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'
Aapplication/json
Bjson
C"application/json"
D"application/xml"
Attempts:
3 left
💡 Hint
Common Mistakes
Using unquoted strings.
Using wrong MIME types like application/xml.
4fill in blank
hard

Fill 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'
Adata
BjsonObject
CprettyPrinted
DfragmentsAllowed
Attempts:
3 left
💡 Hint
Common Mistakes
Using jsonObject instead of data method.
Passing invalid options.
5fill in blank
hard

Fill 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'
AresponseData
BHTTPURLResponse
C200
DURLResponse
Attempts:
3 left
💡 Hint
Common Mistakes
Using URLResponse instead of HTTPURLResponse for statusCode.
Using wrong status code numbers.