123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353 |
- //
- // AnimationTakeQuizViewController.swift
- // Learn Genie
- //
- // Created by Suraj Kumar Mandal on 31/01/22.
- //
- import UIKit
- import Alamofire
- import RealmSwift
- class AnimationTakeQuizViewController: UIViewController {
-
- @IBOutlet var backgroundImageView: UIImageView!
- @IBOutlet var timerLabel: UILabel!
- @IBOutlet var minuteSecondLabel: UILabel!
- @IBOutlet var questionLabel: UILabel!
- @IBOutlet var animationView: UIView!
- @IBOutlet var cancelButton: UIButton!
-
- //Result submit pop up view outlets
- @IBOutlet var submitPopupView: UIView!
- @IBOutlet var resultImageView: UIImageView!
- @IBOutlet var resultHeadingLabel: UILabel!
- @IBOutlet var resultSubHeadingLabel: UILabel!
- @IBOutlet var tryAgainButton: UIButton!
- @IBOutlet var popUpNextButton: UIButton!
- @IBOutlet var viewAnswerButton: UIButton!
-
- //Playing cards outlets
- @IBOutlet var cardAnimationView: UIView!
- @IBOutlet var frontView1: UIImageView!
- @IBOutlet var backView1: UIView!
- @IBOutlet var frontView2: UIImageView!
- @IBOutlet var backView2: UIView!
- @IBOutlet var frontView3: UIImageView!
- @IBOutlet var backView3: UIView!
- @IBOutlet var frontView4: UIImageView!
- @IBOutlet var backView4: UIView!
-
-
- var circleView: UIView!
-
- var tap: UITapGestureRecognizer!
- var quizTimer = Timer()
- var frameUpdateTimer = Timer()
- var secondsLeft: Int = 300
- var quesIndex = 0
- var selectedAnswer = [SelectedAnswerModel]()
- let studentId = UserDefaultsConstant.getIntValueFromUserDefults(for: Constant.studentId) as! Int
- let levelData = DBManager.sharedInstance.database.objects(LevelModel.self)
-
- var topicId = Int()
- var topicIndex = Int()
- var mainTopicIndex = Int()
- var quesBankId = Int()
- var quesId = Int()
- var selectedChoiceId = Int()
- var answerChoiceId = Int()
- var choiceArray = [Int]()
-
- var imageArray1 = ["planet", "piggiebank", "playingCardBack"]
- var imageArray2 = ["balloon", "coin"]
-
- //Not changing values in quiz process
- var levelId = Int()
- var runs = Int()
- var wickets = Int()
-
- var choice4Image = String()
- var choice2Image = String()
-
- var balloon1 : UIImageView!
- var balloon2 : UIImageView!
-
- // Planets view setup
- // 1
- private lazy var planet1: UIView = {
- let view = UIView()
- view.translatesAutoresizingMaskIntoConstraints = false
- view.clipsToBounds = true
- view.isUserInteractionEnabled = true
- view.alpha = 1.0
-
- var imageView : UIImageView
- imageView = UIImageView(frame:CGRect(x: 0, y: 0, width: 150, height: 150));
- view.addSubview(imageView)
-
- let tap = UITapGestureRecognizer(target: self, action: #selector(AnimationTakeQuizViewController.planet1Tap(_:)))
- tap.numberOfTapsRequired = 1
- tap.numberOfTouchesRequired = 1
- view.addGestureRecognizer(tap)
- let label = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
- label.center = CGPoint(x: 75, y: 75)
- label.textAlignment = .center
- label.numberOfLines = 0
- label.textColor = UIColor.black
- label.font = UIFont.systemFont(ofSize: 14)
- view.addSubview(label)
- //label.translatesAutoresizingMaskIntoConstraints = true
- // view.addConstraint(NSLayoutConstraint(item: label, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 10))
- // view.addConstraint(NSLayoutConstraint(item: label, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 10))
- // label.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
- // label.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
-
- return view
- }()
- // 2
- private lazy var planet2: UIView = {
- let view = UIView()
- view.translatesAutoresizingMaskIntoConstraints = false
- view.clipsToBounds = true
- view.isUserInteractionEnabled = true
- view.alpha = 1.0
-
- var imageView : UIImageView
- imageView = UIImageView(frame:CGRect(x: 0, y: 0, width: 150, height: 150));
- view.addSubview(imageView)
-
- let tap = UITapGestureRecognizer(target: self, action: #selector(AnimationTakeQuizViewController.planet2Tap(_:)))
- tap.numberOfTapsRequired = 1
- tap.numberOfTouchesRequired = 1
- view.addGestureRecognizer(tap)
- let label = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
- label.center = CGPoint(x: 75, y: 75)
- label.textAlignment = .center
- label.numberOfLines = 0
- label.textColor = UIColor.black
- label.font = UIFont.systemFont(ofSize: 14)
- view.addSubview(label)
-
- return view
- }()
- // 3
- private lazy var planet3: UIView = {
- let view = UIView()
- view.translatesAutoresizingMaskIntoConstraints = false
- view.clipsToBounds = true
- view.isUserInteractionEnabled = true
- view.alpha = 1.0
-
- var imageView : UIImageView
- imageView = UIImageView(frame:CGRect(x: 0, y: 0, width: 150, height: 150));
- view.addSubview(imageView)
-
- let tap = UITapGestureRecognizer(target: self, action: #selector(AnimationTakeQuizViewController.planet3Tap(_:)))
- tap.numberOfTapsRequired = 1
- tap.numberOfTouchesRequired = 1
- view.addGestureRecognizer(tap)
- let label = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
- label.center = CGPoint(x: 75, y: 75)
- label.textAlignment = .center
- label.numberOfLines = 0
- label.textColor = UIColor.black
- label.font = UIFont.systemFont(ofSize: 14)
- view.addSubview(label)
-
- return view
- }()
- // 4
- private lazy var planet4: UIView = {
- let view = UIView()
- view.translatesAutoresizingMaskIntoConstraints = false
- view.clipsToBounds = true
- view.isUserInteractionEnabled = true
- view.alpha = 1.0
-
- var imageView : UIImageView
- imageView = UIImageView(frame:CGRect(x: 0, y: 0, width: 150, height: 150));
- view.addSubview(imageView)
-
- let tap = UITapGestureRecognizer(target: self, action: #selector(AnimationTakeQuizViewController.planet4Tap(_:)))
- tap.numberOfTapsRequired = 1
- tap.numberOfTouchesRequired = 1
- view.addGestureRecognizer(tap)
- let label = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
- label.center = CGPoint(x: 75, y: 75)
- label.textAlignment = .center
- label.numberOfLines = 0
- label.textColor = UIColor.black
- label.font = UIFont.systemFont(ofSize: 14)
- view.addSubview(label)
-
- return view
- }()
-
- // private lazy var balloon1: UIView = {
- // let view = UIView()
- // view.translatesAutoresizingMaskIntoConstraints = false
- // view.clipsToBounds = true
- // view.isUserInteractionEnabled = true
- //
- // var imageView : UIImageView
- // imageView = UIImageView(frame:CGRect(x: 0, y: 0, width: 100, height: 100));
- // view.addSubview(imageView)
- //
- // let label = UILabel(frame: CGRect(x: 0, y: 0, width: 100, height: 21))
- // label.center = CGPoint(x: 80, y: 80)
- // label.textAlignment = .center
- // label.textColor = UIColor.black
- // view.addSubview(label)
- //
- // label.translatesAutoresizingMaskIntoConstraints = false
- //
- // view.addConstraint(NSLayoutConstraint(item: label, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1, constant: 10))
- // view.addConstraint(NSLayoutConstraint(item: label, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1, constant: 10))
- // label.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
- // label.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
- //
- // return view
- // }()
-
- override func viewDidLoad() {
- super.viewDidLoad()
- // Do any additional setup after loading the view.
- ApiManager.generateCookie()
- getQuesBankId()
- }
-
- override func viewWillAppear(_ animated: Bool) {
- if let last = levelData.last {
- if last.id == levelData[mainTopicIndex].id {
- popUpNextButton.setTitle(Helper.translateText(inputText: "SUBMIT"), for: .normal)
- } else {
- popUpNextButton.setTitle(Helper.translateText(inputText: "Next"), for: .normal)
- }
- }
- minuteSecondLabel.text = "\(Helper.translateText(inputText: "Minutes")) : \(Helper.translateText(inputText: "Seconds"))"
- cancelButton.setTitle(Helper.translateText(inputText: "CANCEL"), for: .normal)
- tryAgainButton.setTitle(Helper.translateText(inputText: "TRY AGAIN"), for: .normal)
- viewAnswerButton.setTitle(Helper.translateText(inputText: "View Answer"), for: .normal)
- self.quizTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(self.runQuizTimer), userInfo: nil, repeats: true)
- selectedAnswer.removeAll()
- }
-
- override func viewDidDisappear(_ animated: Bool) {
- self.frameUpdateTimer.invalidate()
- }
-
- // Get question and choice id
- func getQuesBankId() {
- let topicData = DBManager.sharedInstance.database.objects(TopicModel.self)
- for item in topicData {
- if self.topicId == item.id {
- self.levelId = item.levelId
- self.quesBankId = item.questionBankId
- self.choiceArray.removeAll()
- let quesBankData = DBManager.sharedInstance.database.objects(QuestionBankModel.self)
- for item in quesBankData {
- if self.quesBankId == item.id {
- print(item.questions[quesIndex])
- let quesData = DBManager.sharedInstance.database.objects(QuestionModel.self)
- for data in quesData {
- if data.id == item.questions[quesIndex].id {
- print("Current Question: \(data.content)")
- self.quesId = data.id
- self.answerChoiceId = data.answerId
- self.questionLabel.text = Helper.translateText(inputText: data.content)
- for choice in data.choices {
- let id = choice.id
- self.choiceArray.append(id)
- }
- }
- }
- }
- }
- }
- }
- print("Current choices: \(choiceArray)")
- setupAnimation()
- }
-
- func setupAnimation() {
- if choiceArray.count == 4 {
- //Remove all subview from animation view
- for view in self.animationView.subviews {
- view.removeFromSuperview()
- }
- // Random image for choices set
- choice4Image = imageArray1.randomElement()!
- // Background Image set
- if choice4Image == "planet" {
- backgroundImageView.image = UIImage(named: "i_background_space")
- animationView.isHidden = false
- cardAnimationView.isHidden = true
- } else if choice4Image == "piggiebank" {
- backgroundImageView.image = UIImage(named: "i_background_target")
- animationView.isHidden = false
- cardAnimationView.isHidden = true
- } else {
- backgroundImageView.image = UIImage(named: "i_background_target")
- animationView.isHidden = true
- cardAnimationView.isHidden = false
- for view in self.backView1.subviews {
- view.removeFromSuperview()
- }
- for view in self.backView2.subviews {
- view.removeFromSuperview()
- }
- for view in self.backView3.subviews {
- view.removeFromSuperview()
- }
- for view in self.backView4.subviews {
- view.removeFromSuperview()
- }
- }
- //Planet animation setup
- planetSetup { (success) -> Void in
- if success {
- // do second task if success
- //Planet animation start
- startAnimating()
- }
- }
- //Timer to get updated location of planet views
- frameUpdateTimer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(self.update), userInfo: nil, repeats: true)
- } else {
- animationView.isHidden = false
- cardAnimationView.isHidden = true
- frameUpdateTimer.invalidate()
- //Remove all subview from animation view
- for view in self.animationView.subviews {
- view.removeFromSuperview()
- }
- // Random image for choices set
- choice2Image = imageArray2.randomElement()!
- // Images setup
- balloonImageSetup()
- // Background Image set
- if choice2Image == "coin" {
- backgroundImageView.image = UIImage(named: "i_background_coin")
- } else {
- backgroundImageView.image = UIImage(named: "i_background_target")
- }
- //Planet animation setup
- balloonSetup { (success) -> Void in
- if success {
- // do second task if success
- //Balloon animation start
- balloonAnimation1()
- balloonAnimation2()
- }
- }
- //Tag gesture on balloon view
- tap = UITapGestureRecognizer(target: self, action: #selector(AnimationTakeQuizViewController.viewTap(_:)))
- view.addGestureRecognizer(tap)
- }
- }
-
- //Function to setup planet views
- func planetSetup(completion: (_ success: Bool) -> Void) {
- if choice4Image == "playingCardBack" {
- //Card 1
- frontView1.isHidden = false
- frontView1.layer.cornerRadius = 10
-
- backView1.layer.borderWidth = 4
- backView1.layer.cornerRadius = 10
- backView1.layer.borderColor = UIColor.black.cgColor
- backView1.backgroundColor = UIColor.white
- backView1.alpha = 1.0
-
- backView1.isHidden = true
-
- let imageView1 = UIImageView(frame: CGRect(x: 0, y: 0, width: backView1.frame.width - 10, height: backView1.frame.height - 10))
- imageView1.image = UIImage(named: "spades")
- imageView1.clipsToBounds = true
- imageView1.contentMode = .scaleAspectFit
- imageView1.center = backView1.center
- backView1.addSubview(imageView1)
-
- let label1 = UILabel(frame: CGRect(x: 0, y: 0, width: backView1.frame.width - 5, height: 100))
- label1.center = backView1.center
- label1.textAlignment = .center
- label1.numberOfLines = 0
- label1.text = Helper.translateText(inputText: getChoice(id: choiceArray[0]))
- backView1.addSubview(label1)
-
- //Card 2
- frontView2.isHidden = false
- frontView2.layer.cornerRadius = 10
-
- backView2.layer.borderWidth = 4
- backView2.layer.cornerRadius = 10
- backView2.layer.borderColor = UIColor.black.cgColor
- backView2.backgroundColor = UIColor.white
- backView2.alpha = 1.0
-
- backView2.isHidden = true
-
- let imageView2 = UIImageView(frame: CGRect(x: 0, y: 0, width: backView2.frame.width - 10, height: backView2.frame.height - 10))
- imageView2.image = UIImage(named: "hearts")
- imageView2.clipsToBounds = true
- imageView2.contentMode = .scaleAspectFit
- imageView2.center = backView2.center
- backView2.addSubview(imageView2)
-
- let label2 = UILabel(frame: CGRect(x: 0, y: 0, width: backView2.frame.width - 5, height: 100))
- label2.center = backView2.center
- label2.textAlignment = .center
- label2.numberOfLines = 0
- label2.text = Helper.translateText(inputText: getChoice(id: choiceArray[1]))
- backView2.addSubview(label2)
-
- //Card 3
- frontView3.isHidden = false
- frontView3.layer.cornerRadius = 10
-
- backView3.layer.borderWidth = 4
- backView3.layer.cornerRadius = 10
- backView3.layer.borderColor = UIColor.black.cgColor
- backView3.backgroundColor = UIColor.white
- backView3.alpha = 1.0
-
- backView3.isHidden = true
-
- let imageView3 = UIImageView(frame: CGRect(x: 0, y: 0, width: backView3.frame.width - 10, height: backView3.frame.height - 10))
- imageView3.image = UIImage(named: "diamonds")
- imageView3.clipsToBounds = true
- imageView3.contentMode = .scaleAspectFit
- imageView3.center = backView3.center
- backView3.addSubview(imageView3)
-
- let label3 = UILabel(frame: CGRect(x: 0, y: 0, width: backView3.frame.width - 5, height: 100))
- label3.center = backView3.center
- label3.textAlignment = .center
- label3.numberOfLines = 0
- label3.text = Helper.translateText(inputText: getChoice(id: choiceArray[2]))
- backView3.addSubview(label3)
-
- //Card 4
- frontView4.isHidden = false
- frontView4.layer.cornerRadius = 10
-
- backView4.layer.borderWidth = 4
- backView4.layer.cornerRadius = 10
- backView4.layer.borderColor = UIColor.black.cgColor
- backView4.backgroundColor = UIColor.white
- backView4.alpha = 1.0
-
- backView4.isHidden = true
-
- let imageView4 = UIImageView(frame: CGRect(x: 0, y: 0, width: backView4.frame.width - 10, height: backView4.frame.height - 10))
- imageView4.image = UIImage(named: "clubs")
- imageView4.clipsToBounds = true
- imageView4.contentMode = .scaleAspectFit
- imageView4.center = backView4.center
- backView4.addSubview(imageView4)
-
- let label4 = UILabel(frame: CGRect(x: 0, y: 0, width: backView4.frame.width - 5, height: 100))
- label4.center = backView4.center
- label4.textAlignment = .center
- label4.numberOfLines = 0
- label4.text = Helper.translateText(inputText: getChoice(id: choiceArray[3]))
- backView4.addSubview(label4)
- } else {
- //Circle view setup
- circleView = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 240, height: 240))
- circleView.backgroundColor = UIColor.clear
- animationView.addSubview(circleView)
- circleView.center = CGPoint(x: animationView.frame.size.width/2, y: animationView.frame.size.height/2)
-
- //Add planet1 subview to circle
- //1
- circleView.addSubview(self.planet1)
- planet1.alpha = 1.0
- NSLayoutConstraint.activate([
- self.planet1.widthAnchor.constraint(equalToConstant: 150),
- self.planet1.heightAnchor.constraint(equalToConstant: 150)
- ])
- //2
- circleView.addSubview(self.planet2)
- planet2.alpha = 1.0
- NSLayoutConstraint.activate([
- self.planet2.widthAnchor.constraint(equalToConstant: 150),
- self.planet2.heightAnchor.constraint(equalToConstant: 150)
- ])
- //3
- circleView.addSubview(self.planet3)
- planet3.alpha = 1.0
- NSLayoutConstraint.activate([
- self.planet3.widthAnchor.constraint(equalToConstant: 150),
- self.planet3.heightAnchor.constraint(equalToConstant: 150)
- ])
- //4
- circleView.addSubview(self.planet4)
- planet4.alpha = 1.0
- NSLayoutConstraint.activate([
- self.planet4.widthAnchor.constraint(equalToConstant: 150),
- self.planet4.heightAnchor.constraint(equalToConstant: 150)
- ])
-
- //Choice label text set for planet
- //1
- for subview:AnyObject in planet1.subviews {
- if (subview.isKind(of: UIImageView.self) && subview.tag == 0)
- {
- let imageView = subview as! UIImageView
- imageView.image = UIImage(named: choice4Image)
- }
-
- if (subview.isKind(of: UILabel.self) && subview.tag == 0)
- {
- let label = subview as! UILabel
- label.text = Helper.translateText(inputText: getChoice(id: choiceArray[0]))
- }
- }
- //2
- for subview:AnyObject in planet2.subviews {
- if (subview.isKind(of: UIImageView.self) && subview.tag == 0)
- {
- let imageView = subview as! UIImageView
- imageView.image = UIImage(named: choice4Image)
- }
-
- if (subview.isKind(of: UILabel.self) && subview.tag == 0)
- {
- let label = subview as! UILabel
- label.text = Helper.translateText(inputText: getChoice(id: choiceArray[1]))
- }
- }
- //3
- for subview:AnyObject in planet3.subviews {
- if (subview.isKind(of: UIImageView.self) && subview.tag == 0)
- {
- let imageView = subview as! UIImageView
- imageView.image = UIImage(named: choice4Image)
- }
-
- if (subview.isKind(of: UILabel.self) && subview.tag == 0)
- {
- let label = subview as! UILabel
- label.text = Helper.translateText(inputText: getChoice(id: choiceArray[2]))
- }
- }
- //4
- for subview:AnyObject in planet4.subviews {
- if (subview.isKind(of: UIImageView.self) && subview.tag == 0)
- {
- let imageView = subview as! UIImageView
- imageView.image = UIImage(named: choice4Image)
- }
- if (subview.isKind(of: UILabel.self) && subview.tag == 0)
- {
- let label = subview as! UILabel
- label.text = Helper.translateText(inputText: getChoice(id: choiceArray[3]))
- }
- }
-
- // Circle view round set
- self.circleView.layer.cornerRadius = self.circleView.frame.width / 2.0
- // Planet views position and radius set
- // 1
- self.planet1.layer.cornerRadius = self.planet1.frame.width / 2.0
- self.planet1.center = self.getPoint(for: -90)
- // 2
- self.planet2.layer.cornerRadius = self.planet2.frame.width / 2.0
- self.planet2.center = self.getPoint(for: -180)
- // 3
- self.planet3.layer.cornerRadius = self.planet3.frame.width / 2.0
- self.planet3.center = self.getPoint(for: -270)
- // 4
- self.planet4.layer.cornerRadius = self.planet4.frame.width / 2.0
- self.planet4.center = self.getPoint(for: 0)
- }
- // Call completion, when finished, success or faliure
- completion(true)
- }
-
- func balloonImageSetup() {
- // Balloon image setup
- // 1
- let image5 = UIImage(named: choice2Image)
- balloon1 = UIImageView(image: image5!)
- if choice2Image == "coin" {
- balloon1.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
- } else {
- balloon1.frame = CGRect(x: 0, y: 0, width: 150, height: 150)
- }
- balloon1.image = UIImage(named:choice2Image)
- balloon1.alpha = 1
- let label5 = UILabel(frame: CGRect(x: 0, y: 0, width: 150, height: 21))
- label5.center = CGPoint(x: 75, y: 75)
- label5.textAlignment = .center
- label5.textColor = UIColor.black
- label5.font = UIFont.systemFont(ofSize: 14)
- label5.text = Helper.translateText(inputText: getChoice(id: choiceArray[0]))
- balloon1.addSubview(label5)
- label5.translatesAutoresizingMaskIntoConstraints = false
- //
- // balloon1.addConstraint(NSLayoutConstraint(item: label5, attribute: .trailing, relatedBy: .equal, toItem: balloon1, attribute: .trailing, multiplier: 1, constant: 10))
- balloon1.addConstraint(NSLayoutConstraint(item: label5, attribute: .top, relatedBy: .equal, toItem: balloon1, attribute: .top, multiplier: 1, constant: 50))
- NSLayoutConstraint.activate([
- balloon1.widthAnchor.constraint(equalToConstant: 150),
- balloon1.heightAnchor.constraint(equalToConstant: 150)
- ])
- label5.centerXAnchor.constraint(equalTo: balloon1.centerXAnchor).isActive = true
- //label5.centerYAnchor.constraint(equalTo: balloon1.centerYAnchor).isActive = true
-
- // 2
- let image6 = UIImage(named: choice2Image)
- balloon2 = UIImageView(image: image6!)
- if choice2Image == "coin" {
- balloon2.frame = CGRect(x: 0, y: 0, width: 100, height: 100)
- } else {
- balloon2.frame = CGRect(x: 0, y: 0, width: 150, height: 150)
- }
- balloon2.image = UIImage(named:choice2Image)
- balloon2.alpha = 1
-
- let label6 = UILabel(frame: CGRect(x: 0, y: 0, width: 150, height: 21))
- label6.center = CGPoint(x: 75, y: 75)
- label6.textAlignment = .center
- label6.textColor = UIColor.black
- label6.font = UIFont.systemFont(ofSize: 14)
- label6.text = Helper.translateText(inputText: getChoice(id: choiceArray[1]))
- balloon2.addSubview(label6)
-
- label6.translatesAutoresizingMaskIntoConstraints = false
- //
- // balloon1.addConstraint(NSLayoutConstraint(item: label5, attribute: .trailing, relatedBy: .equal, toItem: balloon1, attribute: .trailing, multiplier: 1, constant: 10))
- balloon2.addConstraint(NSLayoutConstraint(item: label6, attribute: .top, relatedBy: .equal, toItem: balloon2, attribute: .top, multiplier: 1, constant: 50))
- NSLayoutConstraint.activate([
- balloon2.widthAnchor.constraint(equalToConstant: 150),
- balloon2.heightAnchor.constraint(equalToConstant: 150)
- ])
- label6.centerXAnchor.constraint(equalTo: balloon2.centerXAnchor).isActive = true
- //label5.centerYAnchor.constraint(equalTo: balloon1.centerYAnchor).isActive = true
- }
-
- func balloonSetup(completion: (_ success: Bool) -> Void) {
- //Balloon stackview create
- let stackView = UIStackView()
- stackView.axis = .horizontal
- stackView.distribution = .fillEqually
- stackView.alignment = .center
- stackView.spacing = 10.0
- stackView.addArrangedSubview(balloon1)
- stackView.addArrangedSubview(balloon2)
- stackView.translatesAutoresizingMaskIntoConstraints = false
- //Add stack view to animation view
- animationView.addSubview(stackView)
-
- //Constraints set to stackview and animation view
- animationView.addConstraint(NSLayoutConstraint(item: stackView, attribute: .trailing, relatedBy: .equal, toItem: animationView, attribute: .trailing, multiplier: 1, constant: 0))
- animationView.addConstraint(NSLayoutConstraint(item: stackView, attribute: .leading, relatedBy: .equal, toItem: animationView, attribute: .leading, multiplier: 1, constant: 0))
-
- stackView.heightAnchor.constraint(equalToConstant: 150).isActive = true
- stackView.centerXAnchor.constraint(equalTo: self.animationView.centerXAnchor).isActive = true
- stackView.centerYAnchor.constraint(equalTo: self.animationView.centerYAnchor).isActive = true
-
- //Choice label text set for balloon
- //1
- for subview:AnyObject in balloon1.subviews {
- if (subview.isKind(of: UIImageView.self) && subview.tag == 0)
- {
- let imageView = subview as! UIImageView
- imageView.image = UIImage(named: choice2Image)
- }
-
- if (subview.isKind(of: UILabel.self) && subview.tag == 0)
- {
- let label = subview as! UILabel
- label.text = Helper.translateText(inputText: getChoice(id: choiceArray[0]))
- }
- }
- //2
- for subview:AnyObject in balloon2.subviews {
- if (subview.isKind(of: UILabel.self) && subview.tag == 0)
- {
- let label = subview as! UILabel
- label.text = Helper.translateText(inputText: getChoice(id: choiceArray[1]))
- }
- }
- completion(true)
- }
-
- //Function to get updated location of planet views
- @objc func update() {
- let planet1Location = planet1.layer.presentation()?.frame
- planet1.frame = CGRect(x: planet1Location?.origin.x ?? 0.0, y: planet1Location?.origin.y ?? 0.0, width: planet1Location?.size.width ?? 0.0, height: planet1Location?.size.height ?? 0.0)
-
- let planet2Location = planet2.layer.presentation()?.frame
- planet2.frame = CGRect(x: planet2Location?.origin.x ?? 0.0, y: planet2Location?.origin.y ?? 0.0, width: planet2Location?.size.width ?? 0.0, height: planet2Location?.size.height ?? 0.0)
-
- let planet3Location = planet3.layer.presentation()?.frame
- planet3.frame = CGRect(x: planet3Location?.origin.x ?? 0.0, y: planet3Location?.origin.y ?? 0.0, width: planet3Location?.size.width ?? 0.0, height: planet3Location?.size.height ?? 0.0)
-
- let planet4Location = planet4.layer.presentation()?.frame
- planet4.frame = CGRect(x: planet4Location?.origin.x ?? 0.0, y: planet4Location?.origin.y ?? 0.0, width: planet4Location?.size.width ?? 0.0, height: planet4Location?.size.height ?? 0.0)
- }
-
- // MARK: - Animation
-
- func startAnimating() {
- if choice4Image == "playingCardBack" {
- perform(#selector(card1Animate), with: nil, afterDelay: 1)
- perform(#selector(card2Animate), with: nil, afterDelay: 1)
- perform(#selector(card3Animate), with: nil, afterDelay: 1)
- perform(#selector(card4Animate), with: nil, afterDelay: 1)
-
- // Tap gesture assign
- // 1
- let tap1 = UITapGestureRecognizer(target: self, action: #selector(AnimationTakeQuizViewController.planet1Tap(_:)))
- tap1.numberOfTapsRequired = 1
- tap1.numberOfTouchesRequired = 1
- backView1.addGestureRecognizer(tap1)
- // 2
- let tap2 = UITapGestureRecognizer(target: self, action: #selector(AnimationTakeQuizViewController.planet2Tap(_:)))
- tap2.numberOfTapsRequired = 1
- tap2.numberOfTouchesRequired = 1
- backView2.addGestureRecognizer(tap2)
- // 3
- let tap3 = UITapGestureRecognizer(target: self, action: #selector(AnimationTakeQuizViewController.planet3Tap(_:)))
- tap3.numberOfTapsRequired = 1
- tap3.numberOfTouchesRequired = 1
- backView3.addGestureRecognizer(tap3)
- // 4
- let tap4 = UITapGestureRecognizer(target: self, action: #selector(AnimationTakeQuizViewController.planet4Tap(_:)))
- tap4.numberOfTapsRequired = 1
- tap4.numberOfTouchesRequired = 1
- backView4.addGestureRecognizer(tap4)
- } else {
- // 1
- let path = UIBezierPath()
- let initialPoint = self.getPoint(for: -90)
- path.move(to: initialPoint)
- for angle in -89...0 { path.addLine(to: self.getPoint(for: angle)) }
- for angle in 1...270 { path.addLine(to: self.getPoint(for: angle)) }
- path.close()
- // 2
- let path1 = UIBezierPath()
- let initialPoint1 = self.getPoint(for: -180)
- path1.move(to: initialPoint1)
- for angle in -179...0 { path1.addLine(to: self.getPoint(for: angle)) }
- for angle in 1...180 { path1.addLine(to: self.getPoint(for: angle)) }
- path1.close()
- // 3
- let path2 = UIBezierPath()
- let initialPoint2 = self.getPoint(for: -270)
- path2.move(to: initialPoint2)
- for angle in -269...0 { path2.addLine(to: self.getPoint(for: angle)) }
- for angle in 1...90 { path2.addLine(to: self.getPoint(for: angle)) }
- path2.close()
- // 4
- let path3 = UIBezierPath()
- let initialPoint3 = self.getPoint(for: 0)
- path3.move(to: initialPoint3)
- for angle in 1...90 { path3.addLine(to: self.getPoint(for: angle)) }
- for angle in 91...360 { path3.addLine(to: self.getPoint(for: angle)) }
- path.close()
-
- // Set animation to planet views
- self.animate(view: self.planet1, path: path)
- self.animate(view: self.planet2, path: path1)
- self.animate(view: self.planet3, path: path2)
- self.animate(view: self.planet4, path: path3)
- }
- }
-
- private func getPoint(for angle: Int) -> CGPoint {
- // 1
- let radius = Double(self.circleView.layer.cornerRadius)
- // 2
- let radian = Double(angle) * Double.pi / Double(180)
- // 3
- let newCenterX = radius + radius * cos(radian)
- let newCenterY = radius + radius * sin(radian)
-
- return CGPoint(x: newCenterX, y: newCenterY)
- }
-
- //Animation for circular motion
- private func animate(view: UIView, path: UIBezierPath) {
- // 1
- let animation = CAKeyframeAnimation(keyPath: "position")
- // 2
- animation.path = path.cgPath
- // 3
- animation.repeatCount = 10
- // 4
- animation.duration = 20
- // 5
- animation.speed = 1.0
- // 6
- //animation.timeOffset = 0
- // 7
- view.layer.add(animation, forKey: "animation")
- }
-
- //Function to stop planets animation
- func stopAnimation() {
- self.pause(view: self.planet1)
- self.pause(view: self.planet2)
- self.pause(view: self.planet3)
- self.pause(view: self.planet4)
- }
-
- private func pause(view: UIView) {
- let pausedTime = view.layer.convertTime(CACurrentMediaTime(), from: nil)
- view.layer.speed = 0
- view.layer.timeOffset = pausedTime
- view.layer.transform = view.layer.presentation()!.transform
- view.layer.removeAnimation(forKey: "transform")
- }
-
- //Function to resume planets animation
- func resumeAnimation() {
- self.resume(view: self.planet1)
- self.resume(view: self.planet2)
- self.resume(view: self.planet3)
- self.resume(view: self.planet4)
- }
-
- private func resume(view: UIView) {
- let pausedTime = view.layer.timeOffset
- view.layer.speed = 1.0
- view.layer.timeOffset = 0
- let timeSincePause = view.layer.convertTime(CACurrentMediaTime(), from: nil) - pausedTime
- view.layer.beginTime = timeSincePause
- }
-
- // Planets tap gesture function
- // 1
- @objc func planet1Tap(_ sender: UITapGestureRecognizer) {
- if choice4Image == "playingCardBack" {
- backView1.alpha = 0.5
- backView2.alpha = 1.0
- backView3.alpha = 1.0
- backView4.alpha = 1.0
- } else {
- planet1.alpha = 0.5
- planet2.alpha = 1.0
- planet3.alpha = 1.0
- planet4.alpha = 1.0
- }
- self.selectedChoiceId = choiceArray[0]
- //nextQuiz()
- }
- // 2
- @objc func planet2Tap(_ sender: UITapGestureRecognizer) {
- if choice4Image == "playingCardBack" {
- backView1.alpha = 1.0
- backView2.alpha = 0.5
- backView3.alpha = 1.0
- backView4.alpha = 1.0
- } else {
- planet1.alpha = 1.0
- planet2.alpha = 0.5
- planet3.alpha = 1.0
- planet4.alpha = 1.0
- }
- self.selectedChoiceId = choiceArray[1]
- //nextQuiz()
- }
- // 3
- @objc func planet3Tap(_ sender: UITapGestureRecognizer) {
- if choice4Image == "playingCardBack" {
- backView1.alpha = 1.0
- backView2.alpha = 1.0
- backView3.alpha = 0.5
- backView4.alpha = 1.0
- } else {
- planet1.alpha = 1.0
- planet2.alpha = 1.0
- planet3.alpha = 0.5
- planet4.alpha = 1.0
- }
- self.selectedChoiceId = choiceArray[2]
- //nextQuiz()
- }
- // 4
- @objc func planet4Tap(_ sender: UITapGestureRecognizer) {
- if choice4Image == "playingCardBack" {
- backView1.alpha = 1.0
- backView2.alpha = 1.0
- backView3.alpha = 1.0
- backView4.alpha = 0.5
- } else {
- planet1.alpha = 1.0
- planet2.alpha = 1.0
- planet3.alpha = 1.0
- planet4.alpha = 0.5
- }
- self.selectedChoiceId = choiceArray[3]
- //nextQuiz()
- }
-
- // Floating animations
- //1
- func balloonAnimation1() {
- let hover = CABasicAnimation(keyPath: "position")
- hover.isAdditive = true
- hover.fromValue = NSValue(cgPoint: CGPoint(x: 0.0, y: -100.0))
- hover.toValue = NSValue(cgPoint: CGPoint(x: 0.0, y: 100.0))
- hover.autoreverses = true
- hover.duration = 10
- hover.speed = 1.0
- hover.repeatCount = Float.infinity
- balloon1.layer.add(hover, forKey: "myHoverAnimation")
- }
- //2
- func balloonAnimation2() {
- let hover = CABasicAnimation(keyPath: "position")
- hover.isAdditive = true
- hover.fromValue = NSValue(cgPoint: CGPoint(x: 0.0, y: 100.0))
- hover.toValue = NSValue(cgPoint: CGPoint(x: 0.0, y: -100.0))
- hover.autoreverses = true
- hover.duration = 10
- hover.speed = 1.0
- hover.repeatCount = Float.infinity
- balloon2.layer.add(hover, forKey: "myHoverAnimation")
- }
-
- // Pause floating animation
- func pauseLayer(layer : CALayer){
- let pausedTime : CFTimeInterval = layer.convertTime(CACurrentMediaTime(), from: nil)
- layer.speed = 0.0
- layer.timeOffset = pausedTime
- }
-
- // Resume floating animation
- func resumeAnimation(layer : CALayer){
- let pausedTime = layer.timeOffset
- layer.speed = 1.0
- layer.timeOffset = 0.0
- layer.beginTime = 0.0
- let timeSincePause = layer.convertTime(CACurrentMediaTime(), from: nil) - pausedTime
- layer.beginTime = timeSincePause
- }
-
- // Cards animation
- // 1
- @objc func card1Animate() {
- let transitionOptions: UIView.AnimationOptions = [.transitionFlipFromRight, .showHideTransitionViews]
- UIView.transition(with: frontView1, duration: 0.5, options: transitionOptions, animations: { [self] in
- frontView1.isHidden = true
- })
- UIView.transition(with: backView1, duration: 0.5, options: transitionOptions, animations: { [self] in
- backView1.isHidden = false
- })
- }
-
- // 2
- @objc func card2Animate() {
- let transitionOptions: UIView.AnimationOptions = [.transitionFlipFromRight, .showHideTransitionViews]
- UIView.transition(with: frontView2, duration: 0.5, options: transitionOptions, animations: { [self] in
- frontView2.isHidden = true
- })
- UIView.transition(with: backView2, duration: 0.5, options: transitionOptions, animations: { [self] in
- backView2.isHidden = false
- })
- }
-
- // 3
- @objc func card3Animate() {
- let transitionOptions: UIView.AnimationOptions = [.transitionFlipFromRight, .showHideTransitionViews]
- UIView.transition(with: frontView3, duration: 0.5, options: transitionOptions, animations: { [self] in
- frontView3.isHidden = true
- })
- UIView.transition(with: backView3, duration: 0.5, options: transitionOptions, animations: { [self] in
- backView3.isHidden = false
- })
- }
-
- // 4
- @objc func card4Animate() {
- let transitionOptions: UIView.AnimationOptions = [.transitionFlipFromRight, .showHideTransitionViews]
- UIView.transition(with: frontView4, duration: 0.5, options: transitionOptions, animations: { [self] in
- frontView4.isHidden = true
- })
- UIView.transition(with: backView4, duration: 0.5, options: transitionOptions, animations: { [self] in
- backView4.isHidden = false
- })
- }
-
- //Balloons tap gesture functions
- @objc func viewTap(_ sender: UITapGestureRecognizer) {
- let view1Location = sender.location(in: balloon1.superview)
- let view2Location = sender.location(in: balloon2.superview)
- if (balloon1.layer.presentation()?.frame.contains(view1Location))! { // If balloon position is equal to the position in animation view
- self.selectedChoiceId = choiceArray[0]
- //nextQuiz()
- balloon1.alpha = 0.5
- balloon2.alpha = 1.0
- // pauseLayer(layer: balloon1.layer)
- // pauseLayer(layer: balloon2.layer)
- } else if (balloon2.layer.presentation()?.frame.contains(view2Location))! {
- self.selectedChoiceId = choiceArray[1]
- //nextQuiz()
- balloon1.alpha = 1.0
- balloon2.alpha = 0.5
- // pauseLayer(layer: balloon1.layer)
- // pauseLayer(layer: balloon2.layer)
- }
- }
-
- // MARK: - Quiz
-
- // Next quiz navigate
- func nextQuiz() {
- if quesIndex == 4 {
- saveSelectedChoice()
- quizTimer.invalidate()
- Alert.showAlertWithAction(vc: self, title: Helper.translateText(inputText: "Are you sure, you want to submit the quiz?"), message: "\(Helper.translateText(inputText: "You have completed")) \(selectedAnswer.count) \(Helper.translateText(inputText: "out of")) 5 \(Helper.translateText(inputText: "questions"))", alertStyle: .alert, actionTitles: [Helper.translateText(inputText: "CANCEL"), Helper.translateText(inputText: "YES")], actionStyles: [.cancel, .default], actions: [{_ in
- }, {[self]_ in
- getResult()
- saveScoreBoard()
- }])
- } else {
- if quesIndex < 4 {
- saveSelectedChoice()
- quesIndex += 1
- getQuesBankId()
- }
- }
- }
-
- // Quiz timer function
- @objc func runQuizTimer(_ runningTimer: Timer) {
- var minute: Int
- var second: Int
- secondsLeft -= 1
-
- if secondsLeft == 0 || secondsLeft < 0 {
- timerLabel.text = "00 : 00"
- quizTimer.invalidate()
- getResult()
- saveScoreBoard()
- } else {
- minute = (secondsLeft % 3600) / 60
- second = (secondsLeft % 3600) % 60
- timerLabel.text = "\(String(format: "%02d", minute)) : \(String(format: "%02d", second))"
- print()
- }
- }
-
- // Get choice from choice id
- func getChoice(id:Int) -> String {
- let choiceData = DBManager.sharedInstance.database.objects(ChoiceModel.self)
- var choiceString = ""
- for choice in choiceData {
- if id == choice.id {
- choiceString = choice.content
- }
- }
- return choiceString
- }
-
- // Save selected choice
- func saveSelectedChoice() {
- if let row = self.selectedAnswer.firstIndex(where: {$0.quesId == self.quesId}) {
- print("Before update: \(selectedAnswer[row])")
- selectedAnswer[row].choiceId = self.selectedChoiceId
- print("After update: \(selectedAnswer[row])")
- } else {
- let answer = SelectedAnswerModel(quesId: quesId, choiceId: selectedChoiceId, answerId: answerChoiceId)
- selectedAnswer.append(answer)
- }
-
- for item in selectedAnswer {
- print("Saved QuesId: \(item.quesId), Saved ChoiceId: \(item.choiceId), Saved Answer: \(item.answerId)")
- }
- }
-
- // Get selected choice
- func getSelectedChoice() {
- if let row = self.selectedAnswer.firstIndex(where: {$0.quesId == self.quesId}) {
- selectedAnswer[row].choiceId = self.selectedChoiceId
- }
- }
-
- // Get correct choice id
- func getCorrectAnswerNumber() -> Int {
- var score = 0
- for answer in selectedAnswer {
- if answer.choiceId == answer.answerId {
- score += 1
- }
- }
- return score
- }
-
- func getResult() {
- switch getCorrectAnswerNumber() {
- case 0, 1:
- resultImageView.image = UIImage(named: "i_run_out")
- resultHeadingLabel.text = Helper.translateText(inputText: "Oh No You are Out Better luck next time")
- resultSubHeadingLabel.text = "\(Helper.translateText(inputText: "You have got")) \(getCorrectAnswerNumber())/5 \(Helper.translateText(inputText: "questions right"))"
- runs = 0
- wickets = 1
- return
- case 2:
- resultImageView.image = UIImage(named: "i_run_two")
- resultHeadingLabel.text = Helper.translateText(inputText: "It\'s a two Try Again")
- resultSubHeadingLabel.text = "\(Helper.translateText(inputText: "You have got")) \(getCorrectAnswerNumber())/5 \(Helper.translateText(inputText: "questions right"))"
- runs = 0
- wickets = 0
- return
- case 3:
- resultImageView.image = UIImage(named: "i_run_three")
- resultHeadingLabel.text = Helper.translateText(inputText: "It\'s a three Nice Hit")
- resultSubHeadingLabel.text = "\(Helper.translateText(inputText: "You have got")) \(getCorrectAnswerNumber())/5 \(Helper.translateText(inputText: "questions right"))"
- runs = 3
- wickets = 0
- return
- case 4:
- resultImageView.image = UIImage(named: "i_run_four")
- resultHeadingLabel.text = Helper.translateText(inputText: "It\'s a four What a tremendous hit")
- resultSubHeadingLabel.text = "\(Helper.translateText(inputText: "You have got")) \(getCorrectAnswerNumber())/5 \(Helper.translateText(inputText: "questions right"))"
- runs = 4
- wickets = 0
- return
- case 5:
- resultImageView.image = UIImage(named: "i_run_six")
- resultHeadingLabel.text = Helper.translateText(inputText: "It\'s a six What a tremendous hit")
- resultSubHeadingLabel.text = "\(Helper.translateText(inputText: "You have got")) \(getCorrectAnswerNumber())/5 \(Helper.translateText(inputText: "questions right"))"
- runs = 61
- wickets = 0
- return
- default:
- return
- }
- }
-
- // Save score board
- func saveScoreBoard() {
- var saveScore = [SaveScoreBoard]()
- let scoreData = DBManager.sharedInstance.database.objects(SaveScoreBoard.self)
- var itemId = Int()
- var noOfAttempts = Int()
- var totalWickets = Int()
- var totalRuns = Int()
- for quiz in scoreData {
- if quiz.levelId == self.levelId && quiz.topicId == self.topicId {
- itemId = scoreData.count + 1
- noOfAttempts = quiz.noOfAttempts + 1
- totalWickets = quiz.wickets + self.wickets
- if quiz.runs >= self.runs {
- totalRuns = quiz.runs
- } else {
- totalRuns = self.runs
- }
- } else {
- itemId = scoreData.count + 1
- noOfAttempts = 1
- totalWickets = self.wickets
- totalRuns = self.runs
- }
- }
- let newSaveScoreModel = SaveScoreBoard(id: itemId, levelId: levelId, topicId: topicId, runs: totalRuns, wickets: totalWickets, noOfAttempts: noOfAttempts, student: studentId, synced: false)
-
- saveScore.append(newSaveScoreModel)
-
- DBManager.sharedInstance.addData(objs: saveScore)
-
- let quizTakenData = DBManager.sharedInstance.database.objects(SaveScoreBoard.self)
- print("Database Score count: \(quizTakenData.count)")
-
- self.submitPopupView.isHidden = false
-
- // Sync when internet available
- if Reachability.isConnectedToNetwork() {
- // let saveScore = DBManager.sharedInstance.database.objects(SaveScoreBoard.self)
- // var noOfAttempts = 1
- // for quiz in saveScore {
- // if quiz.topicId == self.topicId {
- // noOfAttempts = quiz.noOfAttempts + 1
- // }
- // }
- // saveScoreboard(levelId: self.levelId, topicId: self.topicId, runs: self.runs, wickets: self.wickets, noOfAttempts: noOfAttempts)
- }
- }
-
- // Get topic name
- func getTopicName(id:Int) -> String {
- let topicData = DBManager.sharedInstance.database.objects(TopicModel.self)
- var name = ""
- for item in topicData {
- if id == item.id {
- name = item.name
- break
- }
- }
- return name
- }
-
- func nextTopic(completion: (_ success: Bool) -> Void) {
- if popUpNextButton.currentTitle == Helper.translateText(inputText: "SUBMIT") {
- self.navigationController?.popViewController(animated: true)
- } else {
- if levelData[mainTopicIndex].topics.count == topicIndex + 1 {
- mainTopicIndex += 1
- topicIndex = 0
- print("\(mainTopicIndex), \(topicIndex)")
- } else {
- topicIndex += 1
- print(topicIndex)
- }
- }
- completion(true)
- }
-
- /*
- // MARK: - Navigation
- // In a storyboard-based application, you will often want to do a little preparation before navigation
- override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
- // Get the new view controller using segue.destination.
- // Pass the selected object to the new view controller.
- }
- */
-
- @IBAction func quizButtonAction(_ sender: UIButton) {
- switch sender.tag {
- case 0:
- if quesIndex > 0 {
- quesIndex -= 1
- //getSelectedChoice()
- getQuesBankId()
- //setupAnimation()
- }
- break
- case 1:
- nextQuiz()
- break
- case 2:
- Alert.showAlertWithAction(vc: self, title: Helper.translateText(inputText: "Are you sure you want to exit the quiz?"), message: "", alertStyle: .alert, actionTitles: [Helper.translateText(inputText: "CANCEL"), Helper.translateText(inputText: "YES")], actionStyles: [.cancel, .default], actions: [{_ in
- }, { [self]_ in
- quizTimer.invalidate()
- self.navigationController?.popViewController(animated: true)
- }])
- break
- default:
- break
- }
- }
-
- @IBAction func resultPopupCloseAction(_ sender: Any) {
- submitPopupView.isHidden = true
- }
-
- @IBAction func resultPopupButtonAction(_ sender: UIButton) {
- switch sender.tag {
- case 0:
- submitPopupView.isHidden = true
- self.navigationController?.popViewController(animated: true)
- case 1:
- nextTopic { (success) -> Void in
- if success {
- // do second task if success
- submitPopupView.isHidden = true
- let introVC = self.storyboard?.instantiateViewController(withIdentifier: "IntroductionViewController") as! IntroductionViewController
- introVC.topicName = getTopicName(id: levelData[mainTopicIndex].topics[topicIndex].id)
- introVC.topicId = levelData[mainTopicIndex].topics[topicIndex].id
- introVC.mainTopicIndex = self.mainTopicIndex
- introVC.topicIndex = self.topicIndex
- self.navigationController?.pushViewController(introVC, animated: false)
- }
- }
- case 2:
- //submitPopupView.isHidden = true
- DispatchQueue.main.async {
- let viewAnswerVC = self.storyboard?.instantiateViewController(withIdentifier: "ViewAnswerViewController") as! ViewAnswerViewController
- viewAnswerVC.selectedAnswer.removeAll()
- viewAnswerVC.selectedAnswer = self.selectedAnswer
- //self.navigationController?.pushViewController(viewAnswerVC, animated: true)
- self.present(viewAnswerVC, animated: true, completion: nil)
- }
- default:
- return
- }
- }
- }
- extension AnimationTakeQuizViewController {
- func saveScoreboard(levelId:Int, topicId:Int, runs:Int, wickets:Int, noOfAttempts: Int) {
- let url = "\(ApiUrl.BASE_URL + ApiUrl.API_SCOREBOARD)/save.json"
- print(url)
- let cookieValue = UserDefaultsConstant.getValueFromUserDefults(for: "cookieValue") ?? ""
- let headers: HTTPHeaders = [
- "Content-Type": "application/json",
- "Accept": "application/json",
- "Cookie": "\(Constant.CookieName) = \(cookieValue)"
- ]
- print(headers)
-
- let params: Parameters?
- params = [
- "student" : studentId,
- "level" : levelId,
- "topic" : topicId,
- "runs" : runs,
- "wickets" : wickets,
- "noOfAttempts" : noOfAttempts
- ]
- print(params!)
-
- AF.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
- switch response.result {
- case .success(let value):
- print(value)
- let scoreData = value as! NSDictionary
-
- let student = scoreData.value(forKey: "student") as! NSObject;
- let studentId = student.value(forKey: "id") as! NSNumber;
- let topic = scoreData.value(forKey: "topic") as! NSObject;
- let topicId = topic.value(forKey: "id") as! NSNumber;
- let level = scoreData.value(forKey: "level") as! NSObject;
- let levelId = level.value(forKey: "id") as! NSNumber;
- let runs = scoreData.value(forKey: "runs") as! NSNumber;
- let wickets = scoreData.value(forKey: "wickets") as! NSNumber;
- let noOfAttempts = scoreData.value(forKey: "noOfAttempts") as! NSNumber;
-
- var saveScoreModel = [SaveScoreBoard]()
- let id = saveScoreModel.count + 1
- let newSaveScoreModel = SaveScoreBoard(id: id, levelId: Int(truncating: levelId), topicId: Int(truncating: topicId), runs: Int(truncating: runs), wickets: Int(truncating: wickets), noOfAttempts: Int(truncating: noOfAttempts), student: Int(truncating: studentId), synced: true)
-
- saveScoreModel.append(newSaveScoreModel)
-
- DBManager.sharedInstance.addData(objs: saveScoreModel)
- let saveScoreDB = DBManager.sharedInstance.database.objects(SaveScoreBoard.self)
-
- print("save score count")
- print(saveScoreDB.count)
-
- self.submitPopupView.isHidden = false
- case .failure(let error):
- print(error)
- }
- }
- }
- }
|