Swift
Swift
Finnhub API - Get Stock Quote
See more AI Examples
Demonstrates how to get a stock quote from the Finnhub API.Chilkat Swift Downloads
func chilkatTest() {
var success: Bool = false
// Replace with your actual Finnhub API key.
var apiKey: String? = "YOUR_FINNHUB_API_KEY"
var symbol: String? = "AAPL"
let http = CkoHttp()!
// This is the URL without params.
var urlWithoutParams: String? = "https://finnhub.io/api/v1/quote"
let req = CkoHttpRequest()!
// Add params that will be sent in the URL.
req.addParam(name: "symbol", value: symbol)
req.addParam(name: "token", value: apiKey)
req.httpVerb = "GET"
// Send the request to get the JSON response.
let resp = CkoHttpResponse()!
success = http.httpReq(url: urlWithoutParams, request: req, response: resp)
if success == false {
print("\(http.lastErrorText!)")
return
}
let json = CkoJsonObject()!
resp.getBodyJson(json: json)
var statusCode: Int = resp.statusCode.intValue
print("response status code: \(statusCode)")
json.emitCompact = false
print("\(json.emit()!)")
// Sample result:
// {
// "c": 248.8,
// "d": -4.09,
// "dp": -1.6173,
// "h": 255.493,
// "l": 248.07,
// "o": 253.9,
// "pc": 252.89,
// "t": 1774641600
// }
if statusCode == 200 {
// Add the symbol to the top of the result.
json.addString(at: 0, name: "symbol", value: symbol)
// Rename members for clarification.
json.rename(oldName: "c", newName: "currentPrice")
json.rename(oldName: "d", newName: "change")
json.rename(oldName: "dp", newName: "percentChange")
json.rename(oldName: "h", newName: "high")
json.rename(oldName: "l", newName: "low")
json.rename(oldName: "o", newName: "open")
json.rename(oldName: "pc", newName: "prevClose")
json.rename(oldName: "t", newName: "unixTime")
print("\(json.emit()!)")
}
else {
print("Failed")
}
}