简体   繁体   中英

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.

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
    }
}

你忘了添加.resume()发送的结束请求URLSession.shared.dataTask

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM