ios - 异步加载本地 JSON 文件

标签 ios swift dispatch

我不熟悉 swift 和加载文件的同步/异步方式。 我在本地有一个很大的 JSON 文件,用于一个关于足球的 iPad 应用程序,其中包含足球运动员的名单和统计数据。

目前我将整个玩家列表加载到一个字典数组中 然后我让用户搜索特定播放器

func loadJSON() {
    /// Load Json File
    if let path = Bundle.main.path(forResource: "players", ofType: "json") {
        do {
            let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped)
            let jsonObj = try JSON(data: data)

            /// For Player in JSON Serialize values
            for (_,subJson):(String, JSON) in jsonObj["PackData"]["PlayerData"]["P"] {

                let firstName = subJson["_f"].stringValue
                let lastName = subJson["_s"].stringValue
                let id = subJson["_id"].stringValue
                let dateOfBirth = subJson["_d"].stringValue
                let height = subJson["_h"].stringValue
                let weight = subJson["_w"].stringValue
                let image = subJson["_i"].stringValue


                let player = Player(id: id, firstName: firstName, lastName: lastName, dateOfBirth: dateOfBirth, height: height, weight: weight, image: image)

                /// Append Player in players Array
                players.append(player)

            }

由于我在 ViewDidLoad 中使用了 loadJSON(),当我转到该 View 时,应用会卡住几秒钟并占用大量内存。

在数据库中异步处理/实现类似搜索的正确方法是什么?

编辑: 我已经尝试使用 dispatch DispatchQueue.global(qos: .background).async 但我收到错误:indexPath.row out of range on player = filteredPlayers [indexPath.row]

 // create a cell for each table view row
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    // create a new cell if needed or reuse an old one

    let cell:UITableViewCell = self.searchTableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!
    let player: Player

    /// Return a different table if is searching or not
    if isFiltering() {
        player = filteredPlayers[indexPath.row]
    } else {
        player = players[indexPath.row]
    }
    cell.textLabel?.text = player.firstName! + " " + player.lastName!

    cell.textLabel?.textColor = UIColor.white

    return cell

}

最佳答案

您需要在 DispatchQueue 中使用在后台,

func loadJSON() {
    /// Load Json File
    DispatchQueue.global(qos: .background).async{
        if let path = Bundle.main.path(forResource: "players", ofType: "json") {
            do {
                let data = try Data(contentsOf: URL(fileURLWithPath: path), options: .alwaysMapped)
                let jsonObj = try JSON(data: data)

                /// For Player in JSON Serialize values
                for (_,subJson):(String, JSON) in jsonObj["PackData"]["PlayerData"]["P"] {

                    let firstName = subJson["_f"].stringValue
                    let lastName = subJson["_s"].stringValue
                    let id = subJson["_id"].stringValue
                    let dateOfBirth = subJson["_d"].stringValue
                    let height = subJson["_h"].stringValue
                    let weight = subJson["_w"].stringValue
                    let image = subJson["_i"].stringValue


                    let player = Player(id: id, firstName: firstName, lastName: lastName, dateOfBirth: dateOfBirth, height: height, weight: weight, image: image)

                    /// Append Player in players Array
                    players.append(player)

                }
            }
        }
    }
}

关于ios - 异步加载本地 JSON 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50235546/

相关文章:

ios交叉溶解segue过渡颜色?

ios - Xcode 7 : "No matching provisioning profiles found"

iOS Deep linking and Universal link,如何在ios中进行深度链接

ios - 开发配置文件

ios - '-[UITextField 日期] : unrecognized selector sent to instance 0x7f89277121c0'

php - Apache proxfy_fcgi - 将请求分派(dispatch)到时出错

angular - 在 ngrx effect angular 中做某事之前等待两个序列 Action

ios - SwiftUI - 反转 bool 绑定(bind)

ios - 如何在左侧导航栏项目上添加圆形图像

laravel-5 - 有什么方法可以在laravel 5中发送闭包?