0

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()
} 
QuirckyOrk
  • 47
  • 7
  • 2
    Where did you put that code? In Playgrounds? Where is the call of `getStockPrice()`? – Larme Jun 14 '23 at 21:58
  • I put it in Xcode Command Line Tool. I´ve tried to call with: ```getStockPrice(symbol: "AAPL")``` Both over and under the func – QuirckyOrk Jun 14 '23 at 22:23
  • 2
    The command line app probably exits long before the asynchronous call to get the data has a chance to complete. – HangarRash Jun 15 '23 at 01:18
  • https://stackoverflow.com/questions/31944011/how-to-prevent-a-command-line-tool-from-exiting-before-asynchronous-operation-co – Larme Jun 15 '23 at 07:03
  • Thanks, it worked when the code was put in playground, also when i called the function. Thanks for your help guys! – QuirckyOrk Jun 16 '23 at 23:22

0 Answers0