I am new to swift and the sync/async way to load a file.
I have a big JSON file in local, for an iPad
app about football with the list and stats of football players.
At the moment I load the whole list of players inside an array of dictionaries and I let the user search for the specific player
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)
}
Since I use loadJSON()
in ViewDidLoad
, the app freeze for few seconds and uses a lot of memory when I segue to this view.
What is the proper way to handle/implement something like a search in DB, in async?
EDIT:
I already tried to use dispatch DispatchQueue.global(qos: .background).async
but I get the error: 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
}