0

I do not understand, how I can implement a RapidApi in a Swift Project, what am I doing wrong?

enter image description here

import Foundation
let headers = [
  "x-rapidapi-host": "community-open-weather-map.p.rapidapi.com",
  "x-rapidapi-key": "[your rapidapi key]"
]
let request = NSMutableURLRequest(url: NSURL(string: "https://community-open-weather-map.p.rapidapi.com/weather?q=London%252Cuk")! 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()

how do I have to wrap this, so it works?

Joakim Danielson
  • 43,251
  • 5
  • 22
  • 52
treenera
  • 19
  • 3
  • 3
    You need to create a custom type and add a function to it and then add your code to that function – Joakim Danielson Sep 14 '22 at 19:55
  • 1
    Your code "is nowhere". You can't put code anywhere, there is some logic to comply. Well, Playgrounds, and "Swift scripts/command line tools" are different, but "apps" needs "structure". – Larme Sep 14 '22 at 20:59
  • thanks guys, I copied it from a playground project and now I understand the issue. – treenera Sep 14 '22 at 21:59

1 Answers1

1

You need to encapsulate you block of code in a method -

func getWeatherData() {


let headers = [
  "x-rapidapi-host": "community-open-weather-map.p.rapidapi.com",
  "x-rapidapi-key": "[your rapidapi key]"
]

let request = NSMutableURLRequest(url: NSURL(string: "https://community-open-weather-map.p.rapidapi.com/weather?q=London%252Cuk")! 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()

}

Abhishek
  • 61
  • 4