I have various beginner mistakes, which I am not capable to fix. Some help would be appreciated. Tried to google for it and read apple documentation but did not get far. Here is the code part:
import Foundation
struct StockDataManager {
let headers = [
"x-rapidapi-host": "yahoo-finance15.p.rapidapi.com",
"x-rapidapi-key": "MYAPIKEY"
]
let request = NSMutableURLRequest(url: NSURL(string: "https://yahoo-finance15.p.rapidapi.com/api/yahoo/qu/quote/AAPL/financial-data")! as URL,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse)
}
})
dataTask.resume()
}
I get the follwoing errors at this point:
request.httpMethod = "GET"
And here:
dataTask.resume()
I am pretty sure this is basic understanding and sorry for that stupid simple question. Thanks in advance still for trying to help.
First of all don't use NSURL
and NS(Mutable)URLRequest
in Swift at all. Use the native types.
Any custom code must be run inside a function for example
struct StockDataManager {
func loadData(completion: @escaping (Result<Data, Error>) -> Void) {
let headers = [
"x-rapidapi-host": "yahoo-finance15.p.rapidapi.com",
"x-rapidapi-key": "MYAPIKEY"
]
var request = URLRequest(url: URL(string: "https://yahoo-finance15.p.rapidapi.com/api/yahoo/qu/quote/AAPL/financial-data")!,
cachePolicy: .useProtocolCachePolicy,
timeoutInterval: 10.0)
request.httpMethod = "GET"
request.allHTTPHeaderFields = headers
let session = URLSession.shared
let dataTask = session.dataTask(with: request, completionHandler: { (data, response, error) -> Void in
if let error = error {
completion(.failure(error))
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse)
completion(.success(data!))
}
})
dataTask.resume()
}
}
The loadData
function needs also a completion handler to process the asynchronously received data.