Chet Chet - 4 months ago 16
Swift Question

Swift Firebase persistence

I'm trying to enable Firebase Persistence but my code keeps crashing with

terminating with uncaught exception of type NSException

I have tried the line of code under my viewDidLoad as well as under DataService but I still get the same crash. what do I need to do to resolve this problem I'm facing

import UIKit
import Firebase

class HomeTeamSelectionVC: UIViewController, UITableViewDataSource, UITableViewDelegate {

@IBOutlet weak var tableView: UITableView!

var club: Clubs!
var player = [Players]()
var playerFirstName = String()
var playerLastName = String()
var playerSelected: Bool = false

override func viewDidLoad() {

FIRDatabase.database().persistenceEnabled = true //Correct use of????

CLUB_KEY = club.clubKey

tableView.dataSource = self
tableView.delegate = self

DataService.ds.REF_PLAYERS.queryOrdered(byChild: "clubKey").queryEqual(toValue: club.clubKey).observe(.value, with: { (snapshot) in

print("PLAYERS_COUNT: \(snapshot.childrenCount)")
print("PLAYERS_SNAPSHOT: \(snapshot)")

self.player = []
if let snapshots = snapshot.children.allObjects as? [FIRDataSnapshot] {

for snap in snapshots {
if let playerDict = snap.value as? Dictionary<String, AnyObject> {
let key = snap.key

let players = Players(playerKey: key, dictionary: playerDict)

// self.tableView.reloadData()
}) { (error) in
print("CHET: local error")

func numberOfSections(in tableView: UITableView) -> Int {

return 1

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

return player.count

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

let players = player[indexPath.row]
if let cell = tableView.dequeueReusableCell(withIdentifier: "HomeTeamPlayersCell") as? HomeTeamPlayersCell {
return cell
} else {
return HomeTeamPlayersCell()

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

let players: Players!
players = player[indexPath.row]

print (players.playerKey)
print (players.playerFirstName)
print (players.playerLastName)

dismiss(animated: true, completion: nil)

Answer Source

From Firebase documentation:

Note that this property must be set before creating your first Database reference and only needs to be called once per application.

As such, the standard practice is to set it in your AppDelegate. For instance:

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    FIRDatabase.database().persistenceEnabled = true
    return true