get stocks price from api in swift

To get stock prices from an API in Swift, you will need to make a network request and parse the JSON response. Here's an example using the URLSession API:

main.swift
// Define the API endpoint URL
let apiUrl = URL(string: "https://api.example.com/stocks")

// Create a URLSession instance
let session = URLSession.shared

// Create a data task to make the request
let task = session.dataTask(with: apiUrl) { (data, response, error) in
    // Handle errors
    guard error == nil else {
        print("Error: \(error!)")
        return
    }
    
    // Ensure there is data
    guard let data = data else {
        print("No data received")
        return
    }
    
    do {
        // Parse the JSON response
        let json = try JSONSerialization.jsonObject(with: data, options: [])
        if let stocks = json as? [[String: Any]] {
            for stock in stocks {
                // Access each stock price as required
                let price = stock["price"] as? Double ?? 0.0
                print("Stock price: \(price)")
            }
        }
    } catch {
        print("Error parsing JSON: \(error)")
    }
}

// Start the data task
task.resume()
1000 chars
38 lines

Note that in this example, apiUrl is a placeholder for the actual API endpoint URL. You will need to replace it with the correct URL for the API you are using. Also, the example assumes that the JSON response contains an array of stock objects, each with the price key containing the stock price. You may need to adjust the code to match the actual structure of the JSON response from your API.

related categories

gistlibby LogSnag