Search code examples
swiftnsurlnsmutableurlrequest

Beginners Question: Swift: NSMutableURLRequest


  • Would like to have some simple Stock Data in my project
  • Using the rapidAPI for that

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"
  • Consecutive declarations on a line must be separated by ';'
  • Expected '(' in argument list of function declaration
  • Expected '{' in body of function declaration
  • Expected 'func' keyword in instance method declaration
  • Expected declaration
  • Invalid redeclaration of 'request()'

And here:

dataTask.resume()
  • Consecutive declarations on a line must be separated by ';'
  • Expected '(' in argument list of function declaration
  • Expected '{' in body of function declaration
  • Expected 'func' keyword in instance method declaration

I am pretty sure this is basic understanding and sorry for that stupid simple question. Thanks in advance still for trying to help.


Solution

  • 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.