Performing a network request in Swift involves using the URLSession
API. URLSession
provides a set of classes and methods to connect to an HTTP or HTTPS server and exchange data with it. Here's an example of how to perform a basic HTTP GET request:
main.swift416 chars13 lines
In this example, we are creating a URL object from a URL string, and then creating a URLSessionDataTask object to perform the GET request. The URLSessionDataTask completion closure returns three parameters - data, response, and error. We’re checking for the presence of data and then parsing the JSON data using JSONSerialization.
This is just a basic example and there is a lot more that URLSession can do. For example, you can use different HTTP methods (e.g. POST, PUT, DELETE), set headers, handle cookies, and more.
gistlibby LogSnag