我已经尝试了很多方法,但它们似乎都不起作用。我有这个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中的字符串,它也不会打印任何内容。 最佳答案
您需要通过调用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
}
}
关于ios - 无法从JSON Swift获取数据,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/56926783/