I want to print the current stock price of Apple in the console. The code runs, but it does not print anything. Can someone help me solve this? (I have blurred out my API key)
import Foundation
func getStockPrice(symbol: String) {
let apiKey = "****************"
let symbol = "AAPL"
let urlString = "https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=\(symbol)&apikey=\(apiKey)"
guard let url = URL(string: urlString) else {
print("Invalid URL")
return
}
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if let error = error {
print("Error collecting data: \(error.localizedDescription)")
return
}
guard let data = data else {
print("No data received")
return
}
do {
let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any]
if let globalQuote = json?["Global Quote"] as? [String: Any],
let price = globalQuote["05. price"] as? String {
print("Stock price for \(symbol): \(price)")
} else {
print("Could not get stock price")
}
} catch {
print("Error with JSON-data: \(error.localizedDescription)")
}
}
task.resume()
}