// // TimerController.swift // spotTheSpy // // Created by Paolo Alberti on 14/05/18. // Copyright © 2018 Paolo. All rights reserved. // import UIKit import UserNotifications class TimerController: UIViewController { @IBOutlet var timerView: UIView! @IBOutlet var timerLabel: UILabel! @IBOutlet var accusaBtn: UIButton! @IBOutlet var indovinaBtn: UIButton! @IBOutlet var stopBtn: UIButton! @IBOutlet var mainView: UIView! @IBOutlet var centerImg: UIImageView! var seconds : Double = 0 var timer = Timer() override func viewDidLoad() { super.viewDidLoad() DataManager.shared.TimerC = self DataManager.shared.rimuoviNotifiche() UIApplication.shared.isIdleTimerDisabled = true timerView.cornerRadius = 5 timerView.applyGradient(colours: [grigio, UIColor.white]) timerView.borderWidth = 2 timerView.borderColor = grigioscuro2 stopBtn.cornerRadius = 5; stopBtn.applyGradient(colours: [bluscuro, blu]) stopBtn.borderWidth = 2 stopBtn.borderColor = grigio accusaBtn.cornerRadius = 5; accusaBtn.applyGradient(colours: [bluscuro, blu]) accusaBtn.borderWidth = 2 accusaBtn.borderColor = grigio indovinaBtn.cornerRadius = 5; indovinaBtn.applyGradient(colours: [bluscuro, blu]) indovinaBtn.borderWidth = 2 indovinaBtn.borderColor = grigio centerImg.image = UIImage(named: "spia_"+DataManager.shared.stileGrafica+".jpg") seconds = Double(DataManager.shared.nMinuti) * 60 timerLabel.text = timeString(seconds) timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true) NotificationCenter.default.addObserver(self, selector: #selector(pauseWhenBackground(noti:)), name: .UIApplicationDidEnterBackground, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(willEnterForeground(noti:)), name: .UIApplicationWillEnterForeground, object: nil) accusaBtn.setAttributedTitle(NSAttributedString(string: NSLocalizedString("Accusa", comment: ""), attributes: [NSAttributedStringKey.foregroundColor : UIColor.white]), for: .normal) accusaBtn.titleLabel?.textAlignment = NSTextAlignment.center indovinaBtn.setAttributedTitle(NSAttributedString(string: NSLocalizedString("Indovina", comment: ""), attributes: [NSAttributedStringKey.foregroundColor : UIColor.white]), for: .normal) indovinaBtn.titleLabel?.textAlignment = NSTextAlignment.center stopBtn.setTitle(NSLocalizedString("Concludi", comment: ""), for: .normal) // Ridimensiono la schermata delle Opzioni per i diversi Device (NON uso l'Auto Layout) var scale = self.view.frame.size.width/414 if (UIDevice.current.userInterfaceIdiom == .pad) { scale = self.view.frame.size.height/736 } mainView.transform = CGAffineTransform(scaleX: scale, y: scale) } // Interrompo la Partita @IBAction func partitaFinita(_ sender: Any) { DataManager.shared.lightGen.impactOccurred() Sound.play(file: "click.mp3") // Se la Partita è in corso if seconds > 0 { // Se il timer sta girando if timer.isValid{ let appearance = SCLAlertView.SCLAppearance( kTitleFont: UIFont(name: fontBurbank, size: 26)!, kTextFont: UIFont(name: fontBurbank, size: 20)!, kButtonFont: UIFont(name: fontBurbank, size: 20)!, showCloseButton: false ) let alertView = SCLAlertView(appearance: appearance) alertView.addButton(NSLocalizedString("Concludi", comment: ""), target:self, selector:#selector(TimerController.newGame)) alertView.addButton(NSLocalizedString("Annulla", comment: "")) { print("Si continua ...") } alertView.showWarning(NSLocalizedString("Attenzione", comment: ""), subTitle: NSLocalizedString("Msg_concludi", comment: "")) } // Se il timer è fermo, perché si deve accusare una Spia else { // Si riprende la partita timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true) accusaBtn.setAttributedTitle(NSAttributedString(string: NSLocalizedString("Accusa", comment: ""), attributes: [NSAttributedStringKey.foregroundColor : UIColor.white]), for: .normal) accusaBtn.titleLabel?.textAlignment = NSTextAlignment.center indovinaBtn.setAttributedTitle(NSAttributedString(string: NSLocalizedString("Indovina", comment: ""), attributes: [NSAttributedStringKey.foregroundColor : UIColor.white]), for: .normal) indovinaBtn.titleLabel?.textAlignment = NSTextAlignment.center stopBtn.setTitle(NSLocalizedString("Concludi", comment: ""), for: .normal) } } // Se è già finito il tempo, chiudo la partita e ne inizio una nuova else { newGame() } } // Metto in Pausa il timer per accusare una Spia @IBAction func accusaSpia(_ sender: UIButton) { // Se il timer sta andando if timer.isValid { timer.invalidate() accusaBtn.setAttributedTitle(NSAttributedString(string: NSLocalizedString("Spia si", comment: ""), attributes: [NSAttributedStringKey.foregroundColor : UIColor.white]), for: .normal) accusaBtn.titleLabel?.textAlignment = NSTextAlignment.center indovinaBtn.setAttributedTitle(NSAttributedString(string: NSLocalizedString("Spia no", comment: ""), attributes: [NSAttributedStringKey.foregroundColor : UIColor.white]), for: .normal) indovinaBtn.titleLabel?.textAlignment = NSTextAlignment.center stopBtn.setTitle(NSLocalizedString("Riprendi", comment: ""), for: .normal) } // Altrimenti, ho indovinato la Spia else { Sound.play(file: "vittoria.wav") stopTimer() } } // Interrompo la Partita perché la Spia vuole indovinare il Luogo @IBAction func indovinaLuogo(_ sender: UIButton) { // Se il timer sta andando if timer.isValid { timer.invalidate() let appearance = SCLAlertView.SCLAppearance( kTitleFont: UIFont(name: fontBurbank, size: 26)!, kTextFont: UIFont(name: fontBurbank, size: 20)!, kButtonFont: UIFont(name: fontBurbank, size: 20)!, showCloseButton: false ) let alertView = SCLAlertView(appearance: appearance) alertView.addButton(NSLocalizedString("Indovina", comment: ""), target:self, selector:#selector(TimerController.indovinaLuogoSegreto)) alertView.addButton(NSLocalizedString("Annulla", comment: "")) { self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(self.updateTimer), userInfo: nil, repeats: true) } alertView.showWarning(NSLocalizedString("Attenzione", comment: ""), subTitle: NSLocalizedString("Msg_indovina", comment: "")) } // Altrimenti, non ho indovinato la Spia else { Sound.play(file: "failure.mp3") stopTimer() } } @objc func updateTimer() { if seconds < 1 { self.tempoScaduto() } else { Sound.play(file: "tick.wav") seconds -= 1 timerLabel.text = timeString(seconds) } } func refresh (secs: Double) { self.seconds = self.seconds - secs timerLabel.text = timeString(seconds) timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true) } func tempoScaduto() { if timer.isValid { timer.invalidate() } Sound.play(file: "paparapa.m4a") stopBtn.isHidden = true accusaBtn.setAttributedTitle(NSAttributedString(string: NSLocalizedString("Spia si", comment: ""), attributes: [NSAttributedStringKey.foregroundColor : UIColor.white]), for: .normal) accusaBtn.titleLabel?.textAlignment = NSTextAlignment.center indovinaBtn.setAttributedTitle(NSAttributedString(string: NSLocalizedString("Spia no", comment: ""), attributes: [NSAttributedStringKey.foregroundColor : UIColor.white]), for: .normal) indovinaBtn.titleLabel?.textAlignment = NSTextAlignment.center timerLabel.text = NSLocalizedString("Tempo scaduto", comment: "") } func stopTimer() { if timer.isValid { timer.invalidate() } UIApplication.shared.isIdleTimerDisabled = false seconds = 0 DataManager.shared.rimuoviNotifiche() let myNormalAttributedTitle = NSAttributedString(string: NSLocalizedString("Nuova", comment: ""), attributes: [NSAttributedStringKey.foregroundColor : UIColor.white]) stopBtn.setAttributedTitle(myNormalAttributedTitle, for: .normal) stopBtn.isHidden = false accusaBtn.isHidden = true indovinaBtn.isHidden = true } @objc func newGame() { stopTimer() Sound.play(file: "suspense.mp3") performSegue(withIdentifier: "restartGame", sender: nil) } @objc func indovinaLuogoSegreto() { stopTimer() performSegue(withIdentifier: "mostraLuoghi", sender: nil) } func getTimeDifference(startDate: Date) -> (Double) { let calendar = Calendar.current let components = calendar.dateComponents([.hour, .minute, .second], from: startDate, to: Date()) return Double(components.second!) } @objc func pauseWhenBackground(noti: Notification) { if seconds > 0 && timer.isValid{ self.timer.invalidate() let shared = UserDefaults.standard shared.set(Date(), forKey: "savedTime") DataManager.shared.rimuoviNotifiche() inserisciNotifica() } } @objc func willEnterForeground(noti: Notification) { DataManager.shared.rimuoviNotifiche() if let savedDate = UserDefaults.standard.object(forKey: "savedTime") as? Date { let diffSecs = getTimeDifference(startDate: savedDate) if (diffSecs > 0) { self.refresh(secs: diffSecs) } else { self.tempoScaduto() } } } func timeString(_ time:TimeInterval) -> String { let minutes = Int(time) / 60 let seconds = time - Double(minutes) * 60 return String(format:"%02i:%02i",minutes,Int(seconds)) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "mostraLuoghi" { let controller = (segue.destination as! UINavigationController).topViewController as! LocationsController controller.daSelezionare = true } } func inserisciNotifica() { // creiamo il contenuto della notifica let content = UNMutableNotificationContent() // impostiamo il titolo della notifica prendendo la stringa dal text field apposito content.title = NSLocalizedString("Tempo scaduto", comment: "") // impostmo il sottotitolo //content.subtitle = "Funziono!" // impostiamo il testo della notifica prendendo la stringa dal text field apposito content.body = NSLocalizedString("not_body", comment: "") // impostiamo il suono della notifica //content.sound = UNNotificationSound.default() content.sound = UNNotificationSound.init(named:"paparapa.m4a") // impostiamo la categoria, che altro non è che il nome specificato nel file info.plist content.categoryIdentifier = "testNotifica" // creiamo il trigger con i secondi tra le date let trigger = UNTimeIntervalNotificationTrigger(timeInterval: TimeInterval(self.seconds), repeats: false) // creiamo la richiesta let request = UNNotificationRequest(identifier: "testNotifica", content: content, trigger: trigger) // mandiamo la notifica al sistema che la mostrerà al momento opportuno UNUserNotificationCenter.current().add(request) { (error) in if let errore = error { debugPrint(errore.localizedDescription) } else { debugPrint("--> La notifica uscirà tra \(self.seconds) secondi <--") } } } }