get google stock price in swift

To get Google stock price in Swift, we need to fetch data from an API that provides stock price data. One such API is Alpha Vantage.

Here are the steps that we need to follow:

  1. Sign up for an API key from Alpha Vantage by visiting their website.

  2. Create a new Xcode project and add a networking library like Alamofire to it.

  3. In your ViewController, make an API request to Alpha Vantage with your API key and the symbol of the stock that you want to fetch data for (in this case, we want to fetch data for Google, so the symbol is GOOGL).

    main.swift
    let apiKey = "YOUR_API_KEY"
    let url = "https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=GOOGL&apikey=\(apiKey)"
    
    Alamofire.request(url).responseJSON { response in
        if let json = response.result.value {
            print(json)
        }
    }
    
    247 chars
    9 lines
  4. The response from the API will be in JSON format. You can create a model to parse the JSON data into Swift objects.

    main.swift
    struct Stock {
        let symbol: String
        let price: Double
    }
    
    extension Stock {
        init?(json: [String: Any]) {
            guard let symbol = json["01. symbol"] as? String,
                  let priceString = json["05. price"] as? String,
                  let price = Double(priceString) else {
                return nil
            }
    
            self.symbol = symbol
            self.price = price
        }
    }
    
    385 chars
    18 lines
  5. After parsing the JSON, you can use the Stock object to display the stock price data in your app.

    main.swift
    if let json = response.result.value as? [String: Any] {
        if let quote = json["Global Quote"] as? [String: Any], let stock = Stock(json: quote) {
            print("Symbol: \(stock.symbol)")
            print("Price: \(stock.price)")
        }
    }
    
    236 chars
    7 lines

This is just a basic example of how to fetch and parse stock price data in Swift. There are other APIs that you can use, and you can also display the data in customized views and formats depending on your app's requirements.

gistlibby LogSnag