如何更快地在桌面视图中加载JSON数据?

时间:2017-10-04 23:56:36

标签: json swift

我试图用一个黑客新闻文章列表填充tableViewController。 url请求返回一个Integers数组,这些是每个帖子的ID。

然后我在另一个请求中通过其ID获取当前项目。

有更有效的方法吗?现在,这个tableview需要10秒才能加载。

let baseUrl = URL(string: "https://hacker-news.firebaseio.com/v0/")

// This method fetches all the top stories
func fetchStories() {
        DispatchQueue.main.async {
            let dispatchGroup = DispatchGroup()
            let newsUrl = "\(self.baseUrl!)topstories.json"
            Alamofire.request(newsUrl).responseJSON(completionHandler: { (response) in
                if let json = response.result.value as? NSArray {
                    for item in json {
                        let itemId = "\(item)"
                        dispatchGroup.enter()
                        Story.fetchStory(id: itemId, completion: { (story) in
                            self.stories.append(story)
                            dispatchGroup.leave()
                        })
                    }
                }
                dispatchGroup.notify(queue: .main, execute: {
                    self.storiesUpdated?()
                })
            })
        }
    }


// This method fetches each story by its id

class func fetchStory(id: String, completion: @escaping (Story) -> Swift.Void) {
    let url = URL(string: "https://hacker-news.firebaseio.com/v0/item/\(id).json?print=pretty")
    Alamofire.request(url!).responseJSON(completionHandler: { (response) in
        if let json = response.result.value as? [String:Any] {
            let newStory = Story(dictionary: json)
            completion(newStory)
        }
    })
}

0 个答案:

没有答案