我尝试了很多事情,但似乎都没有用。我有这个JSON
[{"id":"1","name":"Dua Kumayl","location":"IABAT","date":"2019-06-13","Islamic":"Shawwal 8,1440","time":"19:30:00.000000","imageURL":""]
通过此链接:http://iabat.org/data.php
我尝试使用以下代码在Swift中获取数据:
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")
}
}
}
}
但是由于某些原因,它不起作用。即使它是for Event in Events
do / catch中的String,它也不会打印任何内容。
答案 0 :(得分:1)
您需要通过调用dataTask
来启动resume()
,并且始终执行print(error)
来跟踪错误
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
}
}
答案 1 :(得分:0)
您忘记添加.resume()
来在URLSession.shared.dataTask
的末尾发送请求。