To fetch data in Swift, you can use the URLSession API provided by Apple. First, you need to create a URL object from the endpoint you want to fetch data from. Then you can create a data task from the URLSession and start it. Once the data task is completed, you can handle the response data in the completion handler. Here's an example:
main.swift382 chars14 lines
In this example, we create a URL object from https://example.com/data.json
. Then we create a data task with URLSession.shared, which is a shared instance of URLSession. We pass the URL to the data task and specify a completion handler. In the completion handler, we check if there's an error fetching data. If there's no error, we print the response data as a string. Finally, we resume the data task to start fetching data.
gistlibby LogSnag