import UIKit import FBSDKLoginKit import AudioToolbox @objc(DataManager) class DataManager: NSObject { // MARK: - Singleton //***** CODICE SPECIALE CHE TRASFORMA QUESTA CLASSE IN UN SINGLETON (snippet sw_sgt)*****\\ class var sharedInstance:DataManager { get { struct Static { static var instance : DataManager? = nil static var token : dispatch_once_t = 0 } dispatch_once(&Static.token) { Static.instance = DataManager() } return Static.instance! } } //***** FINE CODICE SPECIALE *****\\ // MARK: - variabili globali var listaPremi : [PremioModel] = [] var listaVincite : [VincitaModel] = [] var listaPuntate : [PuntataModel] = [] var sezioniPuntate : [AnyObject!] = [] var puntateHeaders : [String] = [] var listaCronologiaPuntate : [PuntataModel] = [] var listaAmici : [UtenteModel] = [] var sezioniVincite : [AnyObject!] = [] var settimaneHeaders : [String] = [] var sezioniPartecipanti : [AnyObject!] = [] var sezioniPartecipantiPast : [AnyObject!] = [] var periodiTorneo : [AnyObject] = [] var periodiTorneoHeader : [String] = [] var listaTorneiPremi : [PremioModel] = [] var filePath : String! var plistPath : String! var webserverURL : String! var webserverURLv : String! var loggedUser : UtenteModel! var sessionLogin : SessioneLogin! var StartViewC : StartViewController! var StartTabBarC : TabBarController! var ListaPremiC : ListaPremiController! var BidControllerC : BidController! var CronologiaProdottoC : CronologiaProdottoController! var ListaVinciteC : ListaVinciteController! var SchedaUtenteC : SchedaUtenteController! var ListaPuntateC : ListaPuntateController! var ListaAmiciC : ListaAmiciController! var TorneoC : TorneoController! var TorneiC : TorneiController! var TorneoPastC : TorneoPastController! var TorneoPremioC : TorneoPremioController! var FeedbackC : FeedbackController! var puntataVicina : PuntataModel! var user_new_lv : Bool! var newCLP : Int64! var wonCLP : String! var supersonic_loaded : Bool! var getCLP_loaded : Bool! var ads_closed : Bool = false var ads_clp : Bool = false var ads_error : String = "" var fusoOrario : Int = 0 var notifica_premi : Bool! var notifica_premi_futuri : Bool! var tip_mostrato : Bool = false var tip_title : String = "" var tip_body : String = "" var tip_version : String = "" var premiCache = [String:UIImage]() var profiliCache = [String:UIImage]() var premiCacheD = [String:String]() var profiliCacheD = [String:String]() var flagCache = [String:UIImage]() var numberFormatter : NSNumberFormatter! var fullDateFormatter : NSDateFormatter! var dateHourFormatter : NSDateFormatter! var hourFormatter : NSDateFormatter! var dateMedFormatter : NSDateFormatter! var contSectBar : Float = 2.8 var contBar : Float = 0.0 var isVibrating : Bool = false var widthScreen : CGFloat = 0.0 var widthBar : CGFloat = 0.0 // MARK: - Metodi func startDataManager() { self.webserverURL = "https://www.crazylex.com/" self.webserverURLv = "https://www.crazylex.com/v105/" self.fusoOrario = NSTimeZone.localTimeZone().secondsFromGMT checkPremi() checkTorneo() self.filePath = cartellaDocuments() self.sessionLogin = SessioneLogin() self.supersonic_loaded = false self.user_new_lv = false self.getCLP_loaded = false self.notifica_premi = false self.notifica_premi_futuri = false self.newCLP = 0 self.plistPath = filePath + "/ulog.plist" self.numberFormatter = NSNumberFormatter() self.numberFormatter.numberStyle = .DecimalStyle self.numberFormatter.locale = NSLocale.currentLocale() self.numberFormatter.maximumFractionDigits = 2 self.numberFormatter.minimumFractionDigits = 2 self.dateHourFormatter = NSDateFormatter() self.dateHourFormatter.dateStyle = .ShortStyle self.dateHourFormatter.timeStyle = .ShortStyle self.dateMedFormatter = NSDateFormatter() self.dateMedFormatter.dateStyle = .MediumStyle self.dateMedFormatter.timeStyle = .NoStyle self.hourFormatter = NSDateFormatter() self.hourFormatter.dateStyle = .NoStyle self.hourFormatter.timeStyle = .MediumStyle self.fullDateFormatter = NSDateFormatter() self.fullDateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" // Ciclo tra le Notifiche locali, in ricerca delle notifiche da rimuovere, per poterne mettere di nuove for notification in UIApplication.sharedApplication().scheduledLocalNotifications! as [UILocalNotification] { if (notification.userInfo!["UUID"] as! String == "comeBack") { UIApplication.sharedApplication().cancelLocalNotification(notification) } else if (notification.userInfo!["UUID"] as! String == "newPrizes") { UIApplication.sharedApplication().cancelLocalNotification(notification) } else if (notification.userInfo!["UUID"] as! String == "oldPrizes") { UIApplication.sharedApplication().cancelLocalNotification(notification) } else if (notification.userInfo!["UUID"] as! String == "endTournament") { UIApplication.sharedApplication().cancelLocalNotification(notification) } else if (notification.userInfo!["UUID"] as! String == "comeBackCLP") { UIApplication.sharedApplication().cancelLocalNotification(notification) } } // Notifica locale che suonerà dopo 3 giorni, se l'utente non ha aperto l'app nel frattempo var week_seconds: Double = 259200 var notification = UILocalNotification() notification.alertTitle = NSLocalizedString("PUSH1_TITLE", comment: "") notification.alertBody = NSLocalizedString("PUSH1_BODY", comment: "") notification.alertAction = NSLocalizedString("ENTER", comment: "") notification.fireDate = NSDate(timeIntervalSinceNow:week_seconds) notification.soundName = UILocalNotificationDefaultSoundName notification.userInfo = ["UUID": "comeBack"] notification.applicationIconBadgeNumber = 1 UIApplication.sharedApplication().scheduleLocalNotification(notification) // Notifica locale che suonerà dopo 7 giorni, se l'utente non ha aperto l'app nel frattempo, e regalerà 50 CLP week_seconds = 604800 notification = UILocalNotification() notification.alertTitle = NSLocalizedString("PUSH1_TITLE", comment: "") notification.alertBody = NSLocalizedString("PUSH1_BODY", comment: "") notification.alertAction = NSLocalizedString("ENTER", comment: "") notification.fireDate = NSDate(timeIntervalSinceNow:week_seconds) notification.soundName = UILocalNotificationDefaultSoundName notification.userInfo = ["UUID": "comeBackCLP"] notification.applicationIconBadgeNumber = 1 UIApplication.sharedApplication().scheduleLocalNotification(notification) // Notifica locale che avviserà l'utente della fine del Torneo mensile, 4 giorni prima let formatter = NSDateFormatter() formatter.dateFormat = "d" let ultimoDelMese = Int(formatter.stringFromDate(NSDate().endOfMonth()!)) let oggi = Int(formatter.stringFromDate(NSDate())) let giorniAlTorneo = ultimoDelMese! - oggi! let giorniPrima = 2 let giorniNotifica = giorniAlTorneo - giorniPrima let secondiGiorno = 86400 let secondiNotifica : Double = Double(giorniNotifica * secondiGiorno) notification = UILocalNotification() notification.alertTitle = NSLocalizedString("PUSH3_TITLE", comment: "") notification.alertBody = NSLocalizedString("PUSH3_BODY", comment: "") notification.alertAction = NSLocalizedString("ENTER", comment: "") notification.fireDate = NSDate(timeIntervalSinceNow:secondiNotifica) notification.soundName = UILocalNotificationDefaultSoundName notification.userInfo = ["UUID": "endTournament"] notification.applicationIconBadgeNumber = 1 UIApplication.sharedApplication().scheduleLocalNotification(notification) // Carico l'opzione della Vibrazione let userDefaults = NSUserDefaults.standardUserDefaults() if !userDefaults.boolForKey("VideoVibrate") { userDefaults.setBool(false, forKey: "VideoVibrate") } else { self.isVibrating = userDefaults.boolForKey("VideoVibrate") } // Carico un SUGGERIMENTO casuale da mostrare getTip() // Controllo Utente precedentemente loggato if NSFileManager.defaultManager().fileExistsAtPath(plistPath) == true { sessionLogin = NSKeyedUnarchiver.unarchiveObjectWithFile(plistPath) as! SessioneLogin // Se ho un utente loggato in precedenza if sessionLogin.userIsLogged == true { print("Logged from \(sessionLogin.loggedBy)") let id_utente = sessionLogin.userRef let email = sessionLogin.logRef // Nel caso non avvenisse il corretto download dei dati per l'utente loggato logoutUtente() let parameters = ["userRef":id_utente, "logRef":email, "country":countryName()] as Dictionary let urlString = webserverURLv + "user_data.php" request(.POST, URLString: urlString, parameters: parameters).responseJSON {(request, response, JSONn, error) -> Void in if let _ = JSONn { //print("login JSON OK") } else { //print("login JSON Nil") return } let json = JSON(JSONn!) if let risultatoQuery = json["result"].string { switch risultatoQuery { case "OK" : print("Utente loggato - dati Caricati") let utenteLoggato = json["utente"] self.loginUtente(utenteLoggato) // Scrivere qui di seguito le operazioni da eseguire una volta che l'utente ha loggato //self.downloadPuntateGroup() //self.downloadAmici() /*if DataManager.sharedInstance.getCLP_loaded == false { self.ListaPremiC.tabBarController?.selectedIndex = 2 }*/ let step = 1.0 / self.contSectBar dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { dispatch_async(dispatch_get_main_queue()) { DataManager.sharedInstance.StartViewC.updateProgressBar(step) } } case "ACT" : print("Utente in attesa di Attivazione") self.logoutUtente() default : print("Utente bannato / NON trovato") self.logoutUtente() } } } } else { print("No Login? \(sessionLogin.loggedBy)") logoutUtente() DataManager.sharedInstance.getCLP_loaded = true let step = 1.0 / self.contSectBar dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { dispatch_async(dispatch_get_main_queue()) { DataManager.sharedInstance.StartViewC.updateProgressBar(step) } } } } else { print("No ulog.plist") logoutUtente() DataManager.sharedInstance.getCLP_loaded = true let step = 1.0 / self.contSectBar dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { dispatch_async(dispatch_get_main_queue()) { DataManager.sharedInstance.StartViewC.updateProgressBar(step) } } } self.downloadPremiImg() //self.downloadVinciteImg() self.downloadPartecipantiImg() } func salvaSessioneLogin(){ NSKeyedArchiver.archiveRootObject(sessionLogin, toFile: plistPath) } // metodo che avvia il download del JSON dei PREMI func downloadPremi() { let url = webserverURLv + "elenco_premi.php" var listaPremiTemp : [PremioModel] = [] request(.GET, URLString: url).responseJSON { (_, _, JSONn, error) in // controlliamo se c'è un errore e nel caso lo stampiamo in console if let er = error { print(er.localizedDescription) } if let _ = JSONn { print("premi JSON OK") } else { print("premi JSON Nil") return } let json = JSON(JSONn!) for i in 0.. 10800) { self.notifica_premi = true let notification = UILocalNotification() notification.alertTitle = NSLocalizedString("PUSH2_TITLE", comment: "") notification.alertBody = NSLocalizedString("PUSH2_BODY", comment: "") + premio.nomeProdotto + NSLocalizedString("PUSH2_BODY2", comment: "") notification.alertAction = NSLocalizedString("ENTER", comment: "") notification.fireDate = NSDate(timeIntervalSinceNow:Double(secondi-10800)) // e ore prima della fine del premio notification.soundName = UILocalNotificationDefaultSoundName notification.userInfo = ["UUID": "oldPrizes"] notification.applicationIconBadgeNumber = 1 UIApplication.sharedApplication().scheduleLocalNotification(notification) //print(">> notifica Premi in SCADENZA OK >> " + notification.alertBody!) } if giorni > 0 { if giorni == 1 { premio.colore = "g" premio.tempoRimasto = String(giorni) + NSLocalizedString("DAY_LEFT", comment: "") } else { premio.colore = "v" premio.tempoRimasto = String(giorni) + NSLocalizedString("DAYS_LEFT", comment: "") } } else { if ore > 0 { if ore == 1 { premio.tempoRimasto = String(ore) + NSLocalizedString("HOUR_LEFT", comment: "") } else { premio.tempoRimasto = String(ore) + NSLocalizedString("HOURS_LEFT", comment: "") } } else { premio.tempoRimasto = NSLocalizedString("HOURS_LEFT2", comment: "") } premio.colore = "r" } } else { let dataInizio = json[i]["data_inizio"].string let dateFormatter1 = NSDateFormatter() dateFormatter1.dateFormat = "yyyy-MM-dd HH:mm:ss" let data_inizio = dateFormatter1.dateFromString(dataInizio!) let dateFormatter2 = NSDateFormatter() dateFormatter2.dateFormat = "yyyy-MM-dd HH:mm:ss" let data_server = dateFormatter2.dateFromString(server_time) let giorni = NSCalendar.currentCalendar().components(.Day, fromDate: data_server!, toDate: data_inizio!, options: []).day let ore = NSCalendar.currentCalendar().components(.Hour, fromDate: data_server!, toDate: data_inizio!, options: []).hour let secondi = NSCalendar.currentCalendar().components(.Second, fromDate: data_server!, toDate: data_inizio!, options: []).second if giorni > 0 { if giorni == 1 { premio.tempoRimasto = String(giorni) + NSLocalizedString("DAY_YET", comment: "") } else { premio.tempoRimasto = String(giorni) + NSLocalizedString("DAYS_YET", comment: "") } } else { if ore > 0 { if ore == 1 { premio.tempoRimasto = String(ore) + NSLocalizedString("HOUR_YET", comment: "") } else { premio.tempoRimasto = String(ore) + NSLocalizedString("HOURS_YET", comment: "") } } else { premio.tempoRimasto = NSLocalizedString("HOURS_YET2", comment: "") } } if(self.notifica_premi_futuri == false) { self.notifica_premi_futuri = true let notification = UILocalNotification() notification.alertTitle = NSLocalizedString("PUSH4_TITLE", comment: "") notification.alertBody = NSLocalizedString("PUSH4_BODY", comment: "") + premio.nomeProdotto + NSLocalizedString("PUSH4_BODY2", comment: "") notification.alertAction = NSLocalizedString("ENTER", comment: "") notification.fireDate = NSDate(timeIntervalSinceNow:Double(secondi)) notification.soundName = UILocalNotificationDefaultSoundName notification.userInfo = ["UUID": "newPrizes"] notification.applicationIconBadgeNumber = 1 UIApplication.sharedApplication().scheduleLocalNotification(notification) // print(">> notifica Premi Futuri OK >> " + notification.alertBody!) } } } listaPremiTemp.append(premio) } self.listaPremi.removeAll(keepCapacity: false) self.listaPremi = listaPremiTemp print("ricarico Premi in tabella") if self.ListaPremiC != nil { self.ListaPremiC.reloadTable() } } } // metodo che avvia il download del JSON dei PREMI func downloadVincite() { var settimaneHeaderTemp : [String] = [] var sezioniVinciteTemp : [AnyObject!] = [] var settimana : [VincitaModel] = [] var curSection : String = "" let url = webserverURLv + "elenco_vincite.php" request(.GET, URLString: url).responseJSON { (_, _, JSONn, error) in // controlliamo se c'è un errore e nel caso lo stampiamo in console if let er = error { print(er.localizedDescription) } if let _ = JSONn { print("vincite JSON OK") } else { print("vincite JSON Nil") return } let json = JSON(JSONn!) for i in 0.. let url = webserverURLv + "elenco_puntate_group.php" var settimaneHeaderTemp : [String] = [] var sezioniPuntateTemp : [AnyObject!] = [] var settimana : [PuntataModel] = [] var curSection : String = "" request(.POST, URLString: url, parameters: parameters).responseJSON {(request, response, JSONn, error) -> Void in // controlliamo se c'è un errore e nel caso lo stampiamo in console if let er = error { print(er.localizedDescription) } if let _ = JSONn { print("puntate JSON OK") } else { print("puntate JSON Nil") return } let json = JSON(JSONn!) for i in 0.. let url = webserverURLv + "elenco_referrers.php" var listaAmiciTemp : [UtenteModel] = [] request(.POST, URLString: url, parameters: parameters).responseJSON {(request, response, JSONn, error) -> Void in // controlliamo se c'è un errore e nel caso lo stampiamo in console if let er = error { print(er.localizedDescription) } if let _ = JSONn { //print(JSONn) print("amici JSON OK") } else { print("amici JSON Nil") return } let json = JSON(JSONn!) for i in 0.. request(.POST, URLString: url, parameters: parameters).responseJSON {(request, response, JSONn, error) -> Void in // controlliamo se c'è un errore e nel caso lo stampiamo in console if let er = error { print(er.localizedDescription) } if let _ = JSONn { print(JSONn) print("partecipanti JSON OK") } else { //print(request) print("partecipanti JSON Nil") return } let json = JSON(JSONn!) for i in 0.. 0 { sezioniPartecipantiTemp.append(gruppo1) } if gruppo2.count > 0 { sezioniPartecipantiTemp.append(gruppo2) } if gruppo3.count > 0 { sezioniPartecipantiTemp.append(gruppo3) } if gruppo4.count > 0 { sezioniPartecipantiTemp.append(gruppo4) } if gruppo5.count > 0 { sezioniPartecipantiTemp.append(gruppo5) } self.sezioniPartecipanti.removeAll(keepCapacity: false) self.sezioniPartecipanti = sezioniPartecipantiTemp if self.TorneoC != nil { print("ricarico Partecipanti in tabella") self.TorneoC.reloadTable() } } } // metodo che avvia il download del JSON delle PUNTATE func downloadCronologiaPuntate(idProdotto: String) { let idUtente = String(loggedUser.idUtente) let parameters = ["id_utente": idUtente, "id_prodotto": idProdotto] as Dictionary let url = webserverURLv + "elenco_puntate_premio.php" self.listaCronologiaPuntate.removeAll(keepCapacity: false) request(.POST, URLString: url, parameters: parameters).responseJSON {(request, response, JSONn, error) -> Void in // controlliamo se c'è un errore e nel caso lo stampiamo in console if let er = error { print(er.localizedDescription) } if let _ = JSONn { print("cronologia puntate JSON OK") } else { print("cronologia puntate JSON Nil") return } let json = JSON(JSONn!) for i in 0..(start: periodo.startIndex, end: periodo.startIndex.advancedBy(4))) anniHeaderTemp.append(curSection) } // Se ho finito una settimana, e vado a quella precedente if curSection != periodo.substringWithRange(Range(start: periodo.startIndex, end: periodo.startIndex.advancedBy(4))) { sezioniAnniTemp.append(periodi) periodi.removeAll(keepCapacity: false) curSection = periodo.substringWithRange(Range(start: periodo.startIndex, end: periodo.startIndex.advancedBy(4))) anniHeaderTemp.append(curSection) } periodi.append(periodo) } sezioniAnniTemp.append(periodi) // svuotiamo l'array self.periodiTorneo.removeAll(keepCapacity: false) self.periodiTorneo = sezioniAnniTemp // svuotiamo l'array self.periodiTorneoHeader.removeAll(keepCapacity: false) self.periodiTorneoHeader = anniHeaderTemp print("ricarico lista Tornei in tabella") if self.TorneiC != nil { self.TorneiC.reloadTable() } } } // metodo che avvia il download del JSON dei PARTECIPANTI al Torneo mensile func downloadTorneoPast() { var gruppo1 : [PartecipanteModel] = [] var gruppo2 : [PartecipanteModel] = [] var gruppo3 : [PartecipanteModel] = [] var gruppo4 : [PartecipanteModel] = [] var gruppo5 : [PartecipanteModel] = [] var sezioniPartecipantiTemp : [AnyObject!] = [] let idUtente : String if self.sessionLogin.userIsLogged == true { idUtente = String(loggedUser.idUtente) } else { idUtente = "0" } let url = webserverURLv + "elenco_campionato.php" let parameters = ["utente": idUtente, "periodo": self.TorneoPastC.periodo] as Dictionary request(.POST, URLString: url, parameters: parameters).responseJSON {(request, response, JSONn, error) -> Void in // controlliamo se c'è un errore e nel caso lo stampiamo in console if let er = error { print(er.localizedDescription) } if let _ = JSONn { //print(JSONn) print("partecipanti passati JSON OK") } else { //print(request) print("partecipanti passati JSON Nil") return } let json = JSON(JSONn!) for i in 0.. 0 { sezioniPartecipantiTemp.append(gruppo1) } if gruppo2.count > 0 { sezioniPartecipantiTemp.append(gruppo2) } if gruppo3.count > 0 { sezioniPartecipantiTemp.append(gruppo3) } if gruppo4.count > 0 { sezioniPartecipantiTemp.append(gruppo4) } self.sezioniPartecipantiPast.removeAll(keepCapacity: false) self.sezioniPartecipantiPast = sezioniPartecipantiTemp print("ricarico Partecipanti Passati in tabella") self.TorneoPastC.reloadTable() } } // metodo che avvia il download del JSON dei PREMI func downloadTorneoPremi() { let url = webserverURLv + "elenco_campionato_premi.php" self.listaTorneiPremi.removeAll(keepCapacity: false) let parameters = ["periodo": self.TorneoPremioC.periodo] as Dictionary request(.POST, URLString: url, parameters: parameters).responseJSON {(request, response, JSONn, error) -> Void in // controlliamo se c'è un errore e nel caso lo stampiamo in console if let er = error { print(er.localizedDescription) } if let _ = JSONn { print("premi torneo JSON OK") } else { print("premi torneo JSON Nil") return } let json = JSON(JSONn!) for i in 0.. let url = webserverURLv + "puntata_premio.php" request(.POST, URLString: url, parameters: parameters).responseJSON {(request, response, JSONn, error) -> Void in // controlliamo se c'è un errore e nel caso lo stampiamo in console if let er = error { print(er.localizedDescription) } if let _ = JSONn { //print(JSONn) print("puntata premio JSON OK") } else { print("puntate premio JSON Nil") return } let json = JSON(JSONn!) if let risultatoQuery = json["result"].string { switch risultatoQuery { case "OK" : let puntata = PuntataModel() let puntataJSON = json["puntata"] if let val_puntata = puntataJSON["puntata"].string { puntata.puntata = self.numberFormatter.stringFromNumber(Double(val_puntata)!) } if let data_puntata = puntataJSON["data_puntata"].string { let dataTemp = self.fullDateFormatter.dateFromString(data_puntata) puntata.dataPuntata = NSCalendar.currentCalendar().dateByAddingUnit(NSCalendarUnit.Second, value: self.fusoOrario, toDate: dataTemp!, options: NSCalendarOptions.init(rawValue: 0)) //puntata.dataPuntata = self.fullDateFormatter.dateFromString(data_puntata) puntata.dataOra = self.dateHourFormatter.stringFromDate(puntata.dataPuntata) puntata.oraPuntata = self.hourFormatter.stringFromDate(puntata.dataPuntata) puntata.giornoPuntata = self.dateMedFormatter.stringFromDate(puntata.dataPuntata) } self.puntataVicina = puntata self.FeedbackC.caricaPuntataUtente() default : self.puntataVicina = nil self.FeedbackC.caricaPuntataUtente() } } } } func checkPremi(){ let urlString = webserverURLv + "check_premi.php" request(.POST, URLString: urlString, parameters: nil).responseJSON {(request, response, JSONn, error) -> Void in //print("DATA: \(JSONn)\n") if let _ = JSONn { //print("checkPremi JSON OK") } else { //print("checkPremi JSON Nil") return } } } func checkTorneo(){ let formatter = NSDateFormatter() formatter.dateFormat = "d" let today = Int(formatter.stringFromDate(NSDate())) if today < 3 { let urlString = webserverURLv + "check_torneo.php" request(.POST, URLString: urlString, parameters: nil).responseJSON {(request, response, JSONn, error) -> Void in //print("DATA: \(JSONn)\n") if let _ = JSONn { //print("checkTorneo JSON OK") } else { //print("checkTorneo JSON Nil") return } } } } func downloadPremiImg() { let url = webserverURLv + "elenco_premi-cache.php" request(.GET, URLString: url).responseJSON { (_, _, JSONn, error) in // controlliamo se c'è un errore e nel caso lo stampiamo in console if let er = error { print(er.localizedDescription) } if let _ = JSONn { print("CACHE premi JSON OK") } else { print("CACHE premi JSON Nil") return } let json = JSON(JSONn!) var c = Float(json.count) let step : Float if json.count == 0 { c = 1 step = 1.0 / (c * self.contSectBar) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { dispatch_async(dispatch_get_main_queue()) { DataManager.sharedInstance.StartViewC.updateProgressBar(step) } } } else { step = 1.0 / (c * self.contSectBar) } for i in 0.. Void in // controlliamo se c'è un errore e nel caso lo stampiamo in console if let er = error { print(er.localizedDescription) } if let _ = JSONn { //print(JSONn) print("CACHE partecipanti JSON OK") } else { //print(request) print("CACHE partecipanti JSON Nil") return } let json = JSON(JSONn!) var c = Float(json.count) let step : Float if json.count == 0 { c = 1 step = 1.0 / (c * self.contSectBar) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { dispatch_async(dispatch_get_main_queue()) { DataManager.sharedInstance.StartViewC.updateProgressBar(step) } } } else { step = 1.0 / (c * self.contSectBar) } for i in 0.. 0 { if self.ads_clp { self.ads_closed = false let time = dispatch_time(dispatch_time_t(DISPATCH_TIME_NOW), Int64(0.5 * Double(NSEC_PER_SEC))) dispatch_after(time, dispatch_get_main_queue()) { print("aggiornaCLP - vado per Aggiornare CLP") // Imposto e mostro il +1 con fade-in fade-out self.SchedaUtenteC.moreCLP.text = "+ " + String(DataManager.sharedInstance.newCLP) UIView.animateWithDuration(1.0, animations: { self.SchedaUtenteC.moreCLP.alpha = 1 self.SchedaUtenteC.moreCLP.frame = CGRect(x: self.SchedaUtenteC.moreCLP.frame.origin.x, y: self.SchedaUtenteC.moreCLP.frame.origin.y - 15, width: self.SchedaUtenteC.moreCLP.bounds.width, height: self.SchedaUtenteC.moreCLP.bounds.height) self.SchedaUtenteC.labelCLP.text = DataManager.sharedInstance.loggedUser.CLP self.SchedaUtenteC.moreCLP.alpha = 0 }, completion: { finished in self.SchedaUtenteC.moreCLP.frame = CGRect(x: self.SchedaUtenteC.moreCLP.frame.origin.x, y: self.SchedaUtenteC.moreCLP.frame.origin.y + 15, width: self.SchedaUtenteC.moreCLP.bounds.width, height: self.SchedaUtenteC.moreCLP.bounds.height) DataManager.sharedInstance.newCLP = 0 self.SchedaUtenteC.moreCLP.text = "" }) // Se ho fatto un nuovo Livello if DataManager.sharedInstance.user_new_lv == true { UIView.animateWithDuration(0.5, delay: 0, options: .CurveEaseOut, animations: { // Allungo la barra EXP a piena barra self.SchedaUtenteC.curExpView.frame.size.width = CGFloat(self.widthBar) }, completion: { finished in let alertView = SCLAlertView() alertView.addButton(NSLocalizedString("GREAT", comment: "")) { self.SchedaUtenteC.curExpView.frame.size.width = CGFloat(1) self.SchedaUtenteC.curLevLabel.text = "Lv." + String(DataManager.sharedInstance.loggedUser.cur_level) self.SchedaUtenteC.nextLevLabel.text = "Lv." + String(DataManager.sharedInstance.loggedUser.cur_level+1) print("Barra accorciata!") UIView.animateWithDuration(0.5, delay: 0, options: .CurveEaseOut, animations: { let tot_exp = self.loggedUser.exp_to_level let cur_exp = self.loggedUser.cur_exp let larghezza_totEXP = Double(self.widthBar) let larghezza_curEXP = round(larghezza_totEXP * cur_exp / tot_exp)+1 self.SchedaUtenteC.curExpView.frame.size.width = CGFloat(larghezza_curEXP) }, completion: { finished in self.SchedaUtenteC.curLevLabel.text = "Lv." + String(DataManager.sharedInstance.loggedUser.cur_level) self.SchedaUtenteC.nextLevLabel.text = "Lv." + String(DataManager.sharedInstance.loggedUser.cur_level+1) print("Barra allungata!") }) } alertView.showCloseButton = false alertView.showSuccess(NSLocalizedString("CONGRATULATIONS", comment: ""), subTitle: NSLocalizedString("GOT_LEVEL", comment: "") + String(DataManager.sharedInstance.loggedUser.cur_level) + NSLocalizedString("GOT_REWARD", comment: "") + DataManager.sharedInstance.wonCLP + NSLocalizedString("GOT_CLP", comment: "")) print("Mostro popup di congratulazioni!") }) } // Altrimenti incremento solamente la barra del livello else { UIView.animateWithDuration(0.5, delay: 0, options: .CurveEaseOut, animations: { let tot_exp = self.loggedUser.exp_to_level let cur_exp = self.loggedUser.cur_exp let larghezza_totEXP = Double(self.widthBar) let larghezza_curEXP = round(larghezza_totEXP * cur_exp / tot_exp)+1 print("tot_exp: \(tot_exp) - cur_exp: \(cur_exp)") print("tot_exp_bar: \(larghezza_totEXP) - cur_exp_bar: \(larghezza_curEXP)") self.SchedaUtenteC.curExpView.frame.size.width = CGFloat(larghezza_curEXP) }, completion: { finished in self.SchedaUtenteC.curLevLabel.text = "Lv." + String(DataManager.sharedInstance.loggedUser.cur_level) self.SchedaUtenteC.nextLevLabel.text = "Lv." + String(DataManager.sharedInstance.loggedUser.cur_level+1) print("Barra allungata!") }) } } } else { print("aggiornaCLP - non sono pronto ancora") } } // Aggiorno solamente il contatore CLP in mezzo alla view else { print("aggiornaCLP - nessun nuovo CLP") self.SchedaUtenteC.labelCLP.text = self.loggedUser.CLP } } else { self.SchedaUtenteC.labelCLP.text = "" } } } else { print("aggiornaCLP - ads_error: " + self.ads_error) print("aggiornaCLP - ads_clp: \(self.ads_clp)") if ads_error == "KO_DEVICES" && self.ads_clp { print("aggiornaCLP - mostro popup errore device") self.ads_closed = false self.ads_error = "" let message = NSLocalizedString("MULTI_DEVICE", comment: "") let alertView = SCLAlertView() alertView.showCloseButton = false alertView.addButton("OK") { self.logoutUtente() self.SchedaUtenteC.utenteLogin(false) } alertView.showWarning(NSLocalizedString("WARNING", comment: ""), subTitle: message) } else if ads_error == "KO_TIME" && self.ads_clp { print("aggiornaCLP - mostro popup errore hack") self.ads_closed = false self.ads_error = "" let message = NSLocalizedString("TIME_HACK", comment: "") let title = NSLocalizedString("TIME_HACK_TITLE", comment: "") let alertView = SCLAlertView() alertView.showCloseButton = false alertView.addButton("OK") { } alertView.showWarning(title, subTitle: message) } } } // metodo che gestisce l'assegnazione dei CLP dopo la visione di un RewardVideo func RVOK(){ // incremento fin da subito i à per far scorrere la barra //self.newCLP = self.newCLP + 1 let idUtente = String(self.loggedUser.idUtente) let device = UIDevice.currentDevice().modelName + " (" + UIDevice.currentDevice().name + ")" + " " + ez.appVersionAndBuild let parameters = ["id_utente": idUtente, "device": device, "uuid": (UIDevice.currentDevice().identifierForVendor?.UUIDString)!] as Dictionary let urlString = webserverURLv + "CLP_RV-db.php" request(.POST, URLString: urlString, parameters: parameters).responseJSON {(request, response, JSONn, error) -> Void in if let _ = JSONn { print("clp JSON OK") } else { print("clp JSON Nil") return } let json = JSON(JSONn!) // Se ho guadagnato dei CLP facendo il livello if let CLPwon = json["clp"].string { self.wonCLP = CLPwon } else { self.wonCLP = "" } // I CLP effettivamente guadagnati if let CLPnew = json["new_clp"].string { self.newCLP = Int64(CLPnew) } else { self.newCLP = 0 } if let risultatoQuery = json["result"].string { switch risultatoQuery { case "OK" : let utenteLoggato = json["utente"] if let clp = utenteLoggato["punti"].string { DataManager.sharedInstance.loggedUser.CLP = clp } if let cur_level = Int64(utenteLoggato["level"].string!) { if (cur_level != DataManager.sharedInstance.loggedUser.cur_level) { self.user_new_lv = true } else { self.user_new_lv = false } DataManager.sharedInstance.loggedUser.cur_level = cur_level } if let cur_exp = Double(utenteLoggato["exp"].string!) { DataManager.sharedInstance.loggedUser.cur_exp = cur_exp } if let exp_to_level = Double(utenteLoggato["exp_to_level"].string!) { DataManager.sharedInstance.loggedUser.exp_to_level = exp_to_level } print("RVOK - fine") self.ads_clp = true self.ads_error = "" if self.ads_closed { print("RVOK - pronto ad aggiornare") self.aggiornaCLP() } else { print("RVOK - Ads NON chiuso") } case "KO_DEVICES" : print("troppi Devices") self.ads_clp = true self.ads_error = "KO_DEVICES" if self.ads_closed { print("RVOK - pronto ad aggiornare") self.aggiornaCLP() } case "KO_TIME" : print("game hack") self.ads_clp = true self.ads_error = "KO_TIME" if self.ads_closed { print("RVOK - pronto ad aggiornare") self.aggiornaCLP() } default : print("errore assegnazione CLP") } } } } // metodo che riceve un suggerimento da mostrare all'avvio dell'app func getTip(){ let urlString = webserverURLv + "tips.php" request(.POST, URLString: urlString, parameters: nil).responseJSON {(request, response, JSONn, error) -> Void in let json = JSON(JSONn!) print(JSONn) if let titolo = json[NSLocalizedString("TIP_TITLE", comment: "")].string { self.tip_title = titolo } if let corpo = json[NSLocalizedString("TIP_BODY", comment: "")].string { self.tip_body = corpo } if let version = json["version"].string { self.tip_version = version } } } func doubleVibrate() { if self.isVibrating { let systemSoundIDButton : SystemSoundID = 1311 AudioServicesPlaySystemSound(SystemSoundID(systemSoundIDButton)) } } func vibrate() { if self.isVibrating { AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate)) } } func supersonicLoaded() -> Bool { return self.supersonic_loaded } func supersonicLoadedSuccessfull() { self.supersonic_loaded = true } func md5(string string: String) -> [UInt8] { var digest = [UInt8](count: Int(CC_MD5_DIGEST_LENGTH), repeatedValue: 0) if let data = string.dataUsingEncoding(NSUTF8StringEncoding) { CC_MD5(data.bytes, CC_LONG(data.length), &digest) } return digest } func cartellaDocuments() -> String { var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) //print(paths[0] as! String) return paths[0] as String } func getFirstAndLastDateOfMonth(date: NSDate) -> (fistDateOfMonth: NSDate, lastDateOfMonth: NSDate) { let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian) let dateComponents = calendar?.components([.Year, .Month], fromDate: date) let fistDateOfMonth = self.returnedDateForMonth(dateComponents!.month, year: dateComponents!.year, day: 1) let lastDateOfMonth = self.returnedDateForMonth(dateComponents!.month + 1, year: dateComponents!.year, day: 0) print("fistDateOfMonth \(fistDateOfMonth)") print("lastDateOfMonth \(lastDateOfMonth)") return (fistDateOfMonth!,lastDateOfMonth!) } func returnedDateForMonth(month: NSInteger, year: NSInteger, day: NSInteger) -> NSDate? { let components = NSDateComponents() components.day = day components.month = month components.year = year let gregorian = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian) return gregorian!.dateFromComponents(components) } func countryNames() -> NSArray{ let countryCodes = NSLocale.ISOCountryCodes() let countries:NSMutableArray = NSMutableArray() for countryCode in countryCodes{ let dictionary : NSDictionary = NSDictionary(object:countryCode, forKey:NSLocaleCountryCode) //get identifire of the counrty _ = NSLocale.localeIdentifierFromComponents(dictionary as! [String : String]) let locale = NSLocale.currentLocale() //get country name let country = locale.displayNameForKey(NSLocaleCountryCode, value : countryCode) //replace "NSLocaleIdentifier" with "NSLocaleCountryCode" to get language name if country != nil {//check the country name is not nil countries.addObject(country!) } } print("\(countries)") return countries } func countryName() -> String { let locale = NSLocale.currentLocale() let countryCode = locale.objectForKey(NSLocaleCountryCode) let uslocale = NSLocale.init(localeIdentifier: "en_US") let country = uslocale.displayNameForKey(NSLocaleCountryCode, value: countryCode!) if country != nil { return country! } else { return "" } } func testPHP(){ let parameters = ["parametro":"eccomi, sono un parametro"] as Dictionary let urlString = webserverURLv + "TEST.php" request(.POST, URLString: urlString, parameters: parameters).responseJSON {(request, response, JSONn, error) -> Void in //print("REQUEST: \(request)\n") //print("RESPONSE: \(response)\n") //print("ERROR: \(error)\n") print("DATA: \(JSONn)\n") if let _ = JSONn { print("test JSON OK") } else { print("test JSON Nil") return } } } } extension NSDate { var month: String { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "MMMM" return dateFormatter.stringFromDate(self) } var hour0x: String { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "hh" return dateFormatter.stringFromDate(self) } var minute0x: String { let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "mm" return dateFormatter.stringFromDate(self) } func startOfMonth() -> NSDate? { let calendar = NSCalendar.currentCalendar() let currentDateComponents = calendar.components([.Year, .Month], fromDate: self) let startOfMonth = calendar.dateFromComponents(currentDateComponents) return startOfMonth } func dateByAddingMonths(monthsToAdd: Int) -> NSDate? { let calendar = NSCalendar.currentCalendar() let months = NSDateComponents() months.month = monthsToAdd return calendar.dateByAddingComponents(months, toDate: self, options: []) } func endOfMonth() -> NSDate? { let calendar = NSCalendar.currentCalendar() if let plusOneMonthDate = dateByAddingMonths(1) { let plusOneMonthDateComponents = calendar.components([.Year, .Month], fromDate: plusOneMonthDate) let endOfMonth = calendar.dateFromComponents(plusOneMonthDateComponents)?.dateByAddingTimeInterval(-1) return endOfMonth } return nil } } extension String { var md5: String! { let str = self.cStringUsingEncoding(NSUTF8StringEncoding) let strLen = CC_LONG(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding)) let digestLen = Int(CC_MD5_DIGEST_LENGTH) let result = UnsafeMutablePointer.alloc(digestLen) CC_MD5(str!, strLen, result) let hash = NSMutableString() for i in 0..