Customize Consent Preferences

We use cookies to help you navigate efficiently and perform certain functions. You will find detailed information about all cookies under each consent category below.

The cookies that are categorized as "Necessary" are stored on your browser as they are essential for enabling the basic functionalities of the site. ... 

Always Active

Necessary cookies are required to enable the basic features of this site, such as providing secure log-in or adjusting your consent preferences. These cookies do not store any personally identifiable data.

No cookies to display.

Functional cookies help perform certain functionalities like sharing the content of the website on social media platforms, collecting feedback, and other third-party features.

No cookies to display.

Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics such as the number of visitors, bounce rate, traffic source, etc.

No cookies to display.

Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.

No cookies to display.

Advertisement cookies are used to provide visitors with customized advertisements based on the pages you visited previously and to analyze the effectiveness of the ad campaigns.

No cookies to display.

Empowering you to understand your world

How To Send A GET Request From An iOS App (Swift)

By Nicholas Brown

When developing an iOS app, there’s a good chance you’ll need to download data from a server. You can do that using an HTTP GET request. You can obtain data from an API endpoint on a server easily by sending a GET request with the required parameters to the server. The following code example downloads a JSON array containing exchange rates from an exchange’s ‘ticker’ API endpoint and parses the first JSON object in that array to extract the desired exchange rate data. I only parsed the first one (array member 0) to keep this example as short as possible.

Key details:

  • The API endpoint used in the following Swift GET request example is: ‘/api/v3/ticker/price’.
  • The API provider is ‘binance.com’.
  • No parameters were required by this particular endpoint, but other endpoints do require them. A parameter is usually at the end of the URL the GET request is being sent to, starting with a question sign. For example ‘?tradingpair=’ is the parameter required by this endpoint, and you provide it with the trading pair. Like other languages, Swift GET requests encode parameters in the URL instead of in the request body (unlike a POST request).
  • The ‘guard’ statements are there to abandon execution if a task fails. That’s an error-handling method.
  • ‘queue.async’ and ‘DispatchQueue’ code are not required in all cases, but you do need them if you are trying to update a label in UIKit because UIKit requires that you do that on the main thread.

let queue = DispatchQueue(label: “lbPrice”);

queue.async {

            guard let url = URL(string: https://api.binance.com/api/v3/ticker/price) else {return}

            //Preparing and sending off the GET request:

            let task = URLSession.shared.dataTask(with: url) { (data, response, error) in

            guard let dataResponse = data,

                      error == nil else {

                        print(error?.localizedDescription ?? “Response Error”);

                      return }

                do{

                    //Store the server’s response in the jsonResponse variable

                    let jsonResponse = try JSONSerialization.jsonObject(with:

                                                                            dataResponse, options: []);

                    

                    guard let jsonArray = jsonResponse as? [[String: Any]] else {

                        return; //Executed if the statement above fails

                    }

                    //Start parsing out specific values, for example: ‘symbol’ or ‘price’

                    guard let symbol = jsonArray[0][symbol] as? String

                    else

                    {

                        return;

                    }

                    guard let price = jsonArray[0][price] as? String else {

                        return;

                    }

DispatchQueue.main.async {

                        self.priceLB1.text = symbol + “: “ + price; //Update the label on the main thread with the data we downloaded.

                    }

                    

                 } catch let parsingError {

                    print(“Error”, parsingError);

               }

                

            }

        task.resume();

        }

Subscribe to our newsletter
Get notified when new content is published