0

I'm trying to convert my old .js api call into my swift app. In the .js I had to send a query with the api url to decide which fields to receive back.

Like this "https://api.myapi.com/planner?query=" + content.txt

content.txt

{
    places(
        ids:["ABC:StopPlace:8329", "ABC:StopPlace:9237"]
    ) {
        name
        id
        estimatedCalls(timeRange: 72100, numberOfDepartures: 20) {

            realtime
            realtimeState
            expectedDepartureTime
            predictionInaccurate
            destinationDisplay {
                frontText
            }

        }
    }
}

Right now I'm trying this:

func loadR(filename: String ) -> String  {

        let url = Bundle.main.url(forResource: filename, withExtension: "txt")!
        let data = try! Data(contentsOf: url)
        let string = String(data: data, encoding: .utf8)!
        print(string)

        self.load(q: string)
        return string
}


func load(q: String) {
   var urlQ = "https://api.apisite.com/planner?query=" + q

   let url = URL(string: urlQ)!

   URLSession.shared.dataTask(with: url) {(data,resp,error) in
            do {
                if let d = data {
                    print(data)
                    /*
                    let decodedLists = try JSONDecoder().decode([Weather].self, from: d)
                    DispatchQueue.main.async {
                        self.metroTimes = decodedLists

                    }
                    */
                }else {
                    print("No Data")
                }
            } catch {
                print ("Error")
                print(error)

            }

        }.resume()
}

but it throws an error: "Fatal error: Unexpectedly found nil while unwrapping an Optional value:"

What is the correct way to parse this file into a url string?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Cinta
  • 453
  • 5
  • 22
  • You need to point out the exact line causing the crash. – rmaddy Nov 03 '19 at 23:37
  • @rmaddy it throws an error at "let url = URL(string: urlQ)!" – Cinta Nov 04 '19 at 01:01
  • Then `q` must have spaces or other values that must be escaped properly. There are many existing question talking about how to properly escape a query string when building a URL. Search on uses of URLComponents and URLQueryItem for proper solutions. – rmaddy Nov 04 '19 at 01:04

0 Answers0