Here's an example of making a GET request in Swift:
main.swift702 chars24 lines
In the above example, we first create a URL
object from a string representing the endpoint of the API we want to retrieve data from. We then create a URLRequest
object with the URL, which we pass to a URLSession
data task to handle the network request. The dataTask
method takes a closure that will be called when the task has completed, with the response data, response metadata, and any error that occurred during the request.
In the closure, we first check for any errors that occurred during the request. If there were no errors, we check if we have any data in the response, and if so, we convert that data to a string, which we can then print out or use for further processing. Finally, we call the resume
method of the data task to start the network request.
gistlibby LogSnag