我正在获取json数据并将其保存在coredata中。并在“ didFinishLaunchingWithOptions”中调用它。当我在“ viewDidLoad”中获取数据时,问题出在表视图第一次为空时。当我关闭它后重新打开应用程序时,数据将显示在tableView中。请看我的节目
const bundles = [
{ name: 'banana', types: ['esm', 'umd'] },
{ name: 'apple', types: ['umd'] }
];
let newArray = [];
bundles.forEach(bundle => {
bundle.types.map(type => {
newArray.push({ name: bundle.name, type })
});
});
console.log(newArray);
This will output =>
[
{
"name": "banana",
"type": "esm"
},
{
"name": "banana",
"type": "umd"
},
{
"name": "apple",
"type": "umd"
}
]
答案 0 :(得分:0)
在接收到索引之后,您将保存CoreData堆栈。目前,还没有收到任何字典。
您需要DispatchGroup
以便在收到所有故事后得到通知,然后保存上下文。在创建数据任务enter
组之前,请在闭包leave
中创建它(在极端情况下也是如此)。 notify
在最后一次迭代之后被调用。
func fetchTopStories() {
let moc = coreData.persistentContainer.viewContext
let myUrlString = "https://hacker-news.firebaseio.com/v0/topstories.json"
guard let newsUrl = URL(string: myUrlString) else { return }
URLSession.shared.dataTask(with: newsUrl) { (data, responce, err) in
if err != nil{
print("err in fetching data", err!)
return
}
else {
let group = DispatchGroup()
guard let jsonResult = try! JSONSerialization.jsonObject(with: data!) as? [Int] else { return }
for anInt in jsonResult {
let myString = "https://hacker-news.firebaseio.com/v0/item/\(anInt).json"
guard let myUrl = URL(string: myString) else { return }
group.enter()
URLSession.shared.dataTask(with: myUrl, completionHandler: { (data, responce, err) in
if err != nil {
print("err in fetching data", err!)
group.leave()
return
}
else {
guard let allData = try? JSONSerialization.jsonObject(with: data!) as? [String:Any] else {
group.leave()
return
}
var news = News(context: moc)
if let newTitle = (allData!["title"]) as? String{
news.title = newTitle
}
if let newScore = (allData!["score"]) as? Int{
news.score = Int16(newScore)
}
if let newId = (allData!["id"]) as? String{
news.id = Int64(newId)!
}
if let newText = (allData!["text"]) as? String{
news.text = newText
}
if let newUrl = (allData!["url"]) as? String{
news.url = newUrl
}
group.leave()
}
}).resume()
}
group.notify(queue: DispatchQueue.main) {
self.coreData.saveContext()
}
}
}.resume()
}
一些注意事项:
pretty-print
,反序列化程序不会在乎美观。.mutableContainers
。此选项完全没有意义,特别是您不进行任何更改并将结果分配给不可变的常量。NSArray / NSDictionary
。使用本机类型。for
循环来迭代数组。始终使用快速枚举,如果确实需要索引,则还使用for (index, element) in { ... }
语法。error
而不是实际上没有意义的文字字符串"err in fetching data"
。guard let myData = data else{return}
是多余的。如果error
是nil
,则data
不是nil
,反之亦然。