Search code examples
iosjsonswifturlsession

Data not being fetched from JSON Swift


I’ve tried a lot of things and they all don’t seem to work. I have this JSON [{"id":"1","name":"Dua Kumayl","location":"IABAT","date":"2019-06-13","Islamic":"Shawwal 8,1440","time":"19:30:00.000000","imageURL":""] from this link: http://iabat.org/data.php and i tried getting the data in Swift using this code:

import UIKit
   struct Event: Decodable {
       let id, name, location, date: String
       let Islamic, time, imageURL: String
    }
   class EventsViewController: UIViewController {
         override func viewDidLoad() {
             super.viewDidLoad()
             let url = "http://iabat.org/data.php"
             guard let urlObj = URL(string: url) else {return}     
              URLSession.shared.dataTask(with: urlObj) {(data, 
    response, error) in

        do {
            var Events = try JSONDecoder().decode([Event].self, from: 
       data!)

            for Event in Events {
                print("Hi")
                print(Event)
                print(Event.name)
            }
        }
        catch {
            print("error")
            }
        }
    }
}

But for Some Reason, it doesn’t work. And it will also not print anything even if it is a String inside the for Event in Events do/catch.


Solution

  • You need to start the dataTask with calling resume() , also always do print(error) to follow errors if any


     class EventsViewController: UIViewController {
             override func viewDidLoad() {
                 super.viewDidLoad()
                 let url = "http://iabat.org/data.php"
                 guard let urlObj = URL(string: url) else {return}     
                  URLSession.shared.dataTask(with: urlObj) {(data, 
        response, error) in
    
            do {
                var Events = try JSONDecoder().decode([Event].self, from: 
           data!)
    
                for event in Events {
                    print("Hi")
                    print(event)
                    print(event.name)
                }
            }
            catch {
                print(error)
                }
            }.resume() // here
        }
    }