'Swift Playgrounds iPad - parse from json Financial Modelling Prep API

G’day I’m trying to pull financial data from the FMP API.

import SwiftUI
import PlaygroundSupport
import Foundation

let url = URL(string: "https://financialmodelingprep.com/api/v3/income-statement/AAPL?apikey=XXXX")

var request = URLRequest(url: url!)

request.addValue("application/json", forHTTPHeaderField: "Accept") //error flag
let task = URLSession.shared.dataTask(with: url!) { data, response, error in
    guard error == nil else {
        print(error!)
        return
    }
    guard let data = data else {
        print("Data is empty")
        return
    }
    
    let json = try! JSONSerialization.jsonObject(with: data, options: [])
    print(json)
}

task.resume() //error flag
PlaygroundPage.current.needsIndefiniteExecution = true //error flag

This is the code they suggest for swift, but I’m getting errors of “expressions are not allowed at the top level” when I attempt this in Playgrounds on iPad. Any idea what’s going wrong?

Appreciate any help. Cheers



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source