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 which is ‘btcusdt’: ‘http://kompulsa.ch:8080/bncryptoprice?tradingpair=btcusdt‘.
- 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();
}