Created
April 17, 2018 03:26
-
-
Save jasonyunjoonpark/acfb70173aaa4ec1fa45089cbeaeb046 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import UIKit | |
import Firebase | |
class VoteController: UIViewController { | |
//MARK: Global Variables | |
var ref: DatabaseReference? | |
var songs = [Song]() | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
//Check if user is signed into Firebase | |
if let uid = Auth.auth().currentUser?.uid { | |
ref = Database.database().reference() | |
} | |
fetchData { | |
print(self.songs) | |
} | |
} | |
func fetchData(completed: @escaping ()->()) { | |
self.ref?.child("songs").observe(.childAdded, with: { (snapshot) in | |
//Cast Firebase data snapshot as dictionary | |
if let dictionary = snapshot.value as? [String: AnyObject] { | |
let song = Song() | |
var ratio: String? | |
//Store each song's data into Song model | |
song.name = dictionary["name"] as? String | |
song.elo = dictionary["elo"] as? Int | |
song.wins = dictionary["wins"] as? Int | |
song.losses = dictionary["losses"] as? Int | |
if song.losses! != 0 && song.wins! == 0 { | |
ratio = "0%" | |
} | |
if song.losses! == 0 && song.wins! == 0{ | |
ratio = "n/a" | |
} | |
if song.losses! == 0 && song.wins! != 0 { | |
ratio = "100%" | |
} | |
if song.losses! != 0 && song.wins! != 0 { | |
let ratioCalculation = (Double(song.wins!)/((Double(song.wins!)) + (Double(song.losses!))) * 100) | |
let roundedRatioCalculation = Int(round(ratioCalculation)) | |
ratio = "\(roundedRatioCalculation)%" | |
} | |
song.ratio = ratio | |
//Add each song to songs array | |
self.songs.append(song) | |
} | |
completed() | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment