User123
User123

Reputation: 37

API call function Swift not reached?

I'm trying to make an API call in my Swift project, but when I run the code the program doesn't reach past if let decodedJson = try? JSONDecoder().decode(JSONStructure.self, from: data) {

I added some print statements to clarify my issue.

I don't get any errors when I run the code either, but I'm guessing that's because I don't have any catch statements. But even when I added that I still didn't get any error. I don't know if this is related to my issue but I tried using try! instead of try? and then I get this error: Initializer for conditional binding must have Optional type, not 'JSONStructure'.

Here is my API call funciton:

 public func FetchTrip() {
        print("Level 1") //This prints
        Trips.removeAll()
        
        let tripKey = "40892db48b394d3a86b2439f9f3800fd"
        let tripUrl = URL(string: "http://api.sl.se/api2/TravelplannerV3_1/trip.json?key=\(tripKey)&originExtId=\(self.origin.iD)&destExtId=\(self.dest.iD)&Date=\(self.travelDate)&Time=\(self.arrivalTime)&searchForArrival=\(self.searchForArrival)")
        
        URLSession.shared.dataTask(with: tripUrl!) {data, response, error in
            print("Level 2") //This prints
            if let data = data {
                print("Level 3") //This prints
                do {
                    if let decodedJson = try? JSONDecoder().decode(JSONStructure.self, from: data) {
                        print("Level 4") //This does not print
                        // My logic here
                        
            }
        }.resume()

And here is my structures that I use to access the JSON file:


struct JSONStructure: Decodable {
    var Trip: [TripStructure]
}

struct TripStructure: Decodable {
    var LegList: LegListStructure
}

struct LegListStructure: Decodable {
    var Leg: [LegStructure]
}

struct LegStructure: Decodable {
    var Origin: StationStructure
    var Destination: StationStructure
    var Product: ProductStructure
    var name: String
    var type: String
    var dist: String
}

struct StationStructure: Decodable {
    var time: String
    var name: String
    var date: String
}

struct ProductStructure: Decodable {
    var catIn: String
}

If you want to see the JSON file for yourself you can use this URL

Upvotes: 0

Views: 54

Answers (1)

jnpdx
jnpdx

Reputation: 52416

If you were not inside a do { } block, you might use if let decodedJson = try? JSONDecoder().decode(JSONStructure.self, from: data). In that case, decodedJson would only get a value if the try? succeeded.

In your case, since you're inside a do { } block, you should just use:

do {
  let decodedJson = try JSONDecoder().decode(JSONStructure.self, from: data)
  //process decoded values here
  print(decodedJson)
} catch {
  //deal with the error
  print(error)
}

If it fails, it'll go to the catch section.

With the ! as you currently have it, it is implicitly unwrapped, telling the compiler that it will not be nil, which is why the if let call fails here -- there's nothing to optionally bind.

Additional reading:

Upvotes: 1

Related Questions