Skip to content

Instantly share code, notes, and snippets.

@alcidesjunior
Last active March 20, 2020 01:02
Show Gist options
  • Save alcidesjunior/d7899bfbd9fa860c6e4b41aec47030a2 to your computer and use it in GitHub Desktop.
Save alcidesjunior/d7899bfbd9fa860c6e4b41aec47030a2 to your computer and use it in GitHub Desktop.
//
// PlayViewModel.swift
// brasileirao
//
// Created by Alcides Junior on 15/03/20.
//
import Foundation
typealias updateClosure = ()->()
final class PlayViewModel {
fileprivate var networkManager = NetWorkManager()
fileprivate var playPersistence = PlayManager()
fileprivate let defaults = UserDefaults.standard
var plays: [PlayElement] = []{
didSet{
DispatchQueue.main.async {
self.updatedList?()
}
}
}
var updatedList: updateClosure?
var totalPages: Int = 1
var totalResults: Int = 0
var currentRound: Int = 1
init(){
fetchPlays(currentRound: currentRound)
}
func fetchPlays(currentRound: Int = 1){
if CheckInternet.Connection(){
self.networkManager.get(T: Play.self, service: .plays(round: currentRound)) {[weak self] data in
switch data{
case .success(let playResult):
DispatchQueue.main.async {
self?.totalPages = playResult.totalPages
self?.totalResults = playResult.plays.count
self?.defaults.set(self?.totalPages, forKey: "totalPages")
self?.plays.removeAll()
playResult.plays.forEach {
self?.plays.append($0)
//verifying if current data exists in core data
if self?.playPersistence.dataExist(id: $0.id) == false {
//inserting data into coredata
self?.playPersistence.createData(playElement: $0)
}
}
}
case .failure(let error):
print(error)
}
}
} else {
//access and retrieving local data
let playResults = self.playPersistence.retrieveData(round: currentRound)
self.plays.removeAll()
playResults?.forEach({ (playResult) in
let team1 = Team(id: 0, name: "", shortname: playResult.value(forKey: "shortname1") as! String, shield: "")
let team2 = Team(id: 0, name: "", shortname: playResult.value(forKey: "shortname2") as! String, shield: "")
let element = PlayElement(id: playResult.value(forKey: "id") as! Int, teams: [team1, team2], score1: playResult.value(forKey: "score1") as! Int, score2: playResult.value(forKey: "score2") as! Int, datetime: playResult.value(forKey: "datetime") as? String, place: playResult.value(forKey: "place") as? String, round: playResult.value(forKey: "round") as! Int)
plays.append(element)
})
self.totalResults = plays.count
self.totalPages = defaults.integer(forKey: "totalPages")
}
}
func result(_ id: Int = 0)->PlayElement{
return self.plays[id]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment