How to pass data backwards to a view controller after passing forward? - swift

Im developing a quiz app and there is a second view controller that appears after the initial view controller where you are asked to answer a question. On the second view controller you the user must press a button to return to the initial view controller to be asked another question. However when I segue back from the second view controller I believe a new instance of the initial view controller is being created and the user is asked questions they have already answered. The code in the swift file for my initial view controller is constructed that when once a user is asked a question once that question is removed from an array by it's index. How could I make it to where a new instance of the initial view controller isn't created from segueing from the second view controller? Or is there a way the second view controller can access the same methods as the initial view controller?
Here is my code for the initial view controller:
import UIKit
class ViewController: UIViewController {
var questionList = [String]()
func updateCounter() {
counter -= 1
questionTimer.text = String(counter)
if counter == 0 {
timer.invalidate()
wrongSeg()
counter = 15
}
}
func randomQuestion() {
//random question
if questionList.isEmpty {
questionList = Array(QADictionary.keys)
questionTimer.text = String(counter)
}
let rand = Int(arc4random_uniform(UInt32(questionList.count)))
questionLabel.text = questionList[rand]
//matching answer values to go with question keys
var choices = QADictionary[questionList[rand]]!
questionList.remove(at: rand)
//create button
var button:UIButton = UIButton()
//variables
var x = 1
rightAnswerBox = arc4random_uniform(4)+1
for index in 1...4
{
button = view.viewWithTag(index) as! UIButton
if (index == Int(rightAnswerBox))
{
button.setTitle(choices[0], for: .normal)
}
else {
button.setTitle(choices[x], for: .normal)
x += 1
}
randomImage()
}
}
let QADictionary = ["Who is Thor's brother?" : ["Atum", "Loki", "Red Norvell", "Kevin Masterson"], "What is the name of Thor's hammer?" : ["Mjolinr", "Uru", "Stormbreaker", "Thundara"], "Who is the father of Thor?" : ["Odin", "Sif", "Heimdall", "Balder"]]
//wrong view segue
func wrongSeg() {
performSegue(withIdentifier: "incorrectSeg", sender: self)
}
//proceed screen
func rightSeg() {
performSegue(withIdentifier: "correctSeg", sender: self)
}
//variables
var rightAnswerBox:UInt32 = 0
var index = 0
//Question Label
#IBOutlet weak var questionLabel: UILabel!
//Answer Button
#IBAction func buttonAction(_ sender: AnyObject) {
if (sender.tag == Int(rightAnswerBox))
{
rightSeg()
print ("Correct!")
}
if counter != 0 {
counter = 15
questionTimer.text = String(counter)
}
else if (sender.tag != Int(rightAnswerBox)) {
wrongSeg()
print ("Wrong!")
timer.invalidate()
questionList = []
}
randomQuestion()
}
override func viewDidAppear(_ animated: Bool)
{
randomQuestion()
}
//variables
var counter = 15
var timer = Timer()
#IBOutlet weak var questionTimer: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
timer = Timer.scheduledTimer(timeInterval: 1, target:self, selector: #selector(ViewController.updateCounter), userInfo: nil, repeats: true)
}
Here's the code to the second view controller:
import UIKit
class ContinueScreen: UIViewController {
//correct answer label
#IBOutlet weak var correctLbl: UILabel!
//background photo
#IBOutlet weak var backgroundImage: UIImageView!
func backToQuiz() {
if let nav = self.navigationController {
nav.popViewController(animated: true)
}
else {
self.dismiss(animated: true, completion: nil)
}
}
#IBAction func `continue`(_ sender: Any) {
backToQuiz()
}

What you need, sir is a delegate or an unwind segue. I far prefer delegates because they're easier to understand and I think a bit more powerful.
In your ContinueScreen view controller define a protocol similar to this:
protocol QuizCompletedDelegate {
func completedQuiz()
func canceledQuiz()
}
Also in your ContinueScreen view controller you need to declare an optional delegate of type QuizCompletedDelegate
var delegate: QuizCompletedDelegate?
... and use that delegate to call the functions when appropriate:
#IBAction func didPressContinue(_ sender: Any) {
if allQuestionsAnswered == true {
delegate.completedQuiz()
} else {
delegate.cancelledQuiz()
}
}
In your initial view controller is where you implement the functions for the protocol:
extension ViewController: QuizCompletedDelegate {
func completedQuiz() {
//Handle quiz complete
}
func cancelledQuiz() {
//Handle quiz cancelled
}
}
Then the last thing you need to do is set the delegate of your ContinueScreen view controller in the prepareForSegue function of your initial view controller.
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showContinueScreen" {
let continueVC = segue.destination as! ContinueScreen
continueVC.delegate = self
}
}
Remove the call to randomQuestion() on your initial view controller's ViewDidAppear, and you're in business!

It shouldn't create a new View Controller when you go back. If it does - it's very bad - and you should re-architect the flow of your app... To pass data forward, we should use Dependency Injection. To pass data to the previous view controller - use the iOS Delegation Pattern. I recommend to spend 30-40 mins to read (and understand this article), and it will make things more clear for you in the future: http://matteomanferdini.com/how-ios-view-controllers-communicate-with-each-other/.

Related

Swift Delegates not working for updating timer to receiver

I have created protocol as updateTime protocol to update timer to other view controllers conform to updateTime delegates but the timer not updating to other controllers.
Please refer below code and pin point where I did wrong?
protocol UpdateTime: class {
func updateTIme(count: Int)
}
class ViewController: UIViewController, UpdateTime {
#IBOutlet var timeLabel: UILabel!
let secVC = SecondViewController()
override func viewDidLoad() {
super.viewDidLoad()
secVC.delegate = self
// Do any additional setup after loading the view.
}
// must be internal or public.
func updateTIme(count: Int){
print("firstVC: \(count)")
DispatchQueue.main.async {
self.timeLabel.text = "\(count)"
}
}
}
class Counter {
var count = 0
func increment() {
count += 1
}
func increment(by amount: Int) -> Int{
count += amount
print(count)
return count
}
func reset() {
count = 0
}
}
This is seconviewcontroller:
class SecondViewController: UIViewController {
#IBOutlet var label: UILabel!
weak var delegate: UpdateTime?
var counter = Counter()
var timer = Timer()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
DispatchQueue.main.async {
self.timer.invalidate()
self.timer = Timer.scheduledTimer(timeInterval: 0.2, target: self, selector: #selector(self.countDown), userInfo: nil, repeats: true)
}
}
#objc func countDown() -> Int{
// counter increments
counter.increment()
let count = counter.increment(by: 5)
DispatchQueue.main.async {
self.label.text = String(describing: count)
}
self.delegate?.updateTIme(count: count)
return count
}
}
The label in view controller not updating count down.
This looks like a lifecycle issue. Though you are creating an instance of SecondViewController, the timer from the second view controller only gets added to the run loop when that view controller's viewDidLoad method is called. Since you are programmatically creating it in the first view controller, there is nowhere in your example that would cause the second view controller's view to get loaded, so the timer would not be added to the runloop.
A better way of accomplishing this issue is to create the timer on the first view controller directly, or create a secondary object (not a second view controller) that manages the timer and have it push updates to the first view controller

How to random position from UIButtons has created by storyboard?[swift Xcode]

I created 12 UIButtons by storyboard, in my program, these buttons represent cards,I want to random the buttons' position for shuffling the cards.please do me a favor, give a way or idea to achieve it.
my buttons problem
import UIKit
class ViewController: UIViewController {
lazy var game = Concentration(numberOfPairsOfCards: numberOfPairOfCards) //引入model Concentration
var numberOfPairOfCards : Int {
return (cardButtons.count + 1) / 2 //read only computed properties可以省略get{}
}
var flipCount = 0 {
didSet {
flipsCountLabel.text = "Flips: \(flipCount)"
}
}
#IBOutlet var cardButtons: [UIButton]!
#IBOutlet weak var flipsCountLabel: UILabel!
#IBAction func touchCard(_ sender: UIButton) {
flipCount += 1
if let cardNumber = cardButtons.index(of: sender) {
game.chooseCard(at: cardNumber)
updateViewFromModel()
} else {
print("somthing wrong")
}
}
I have done the job.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var buttons = [UIButton]()
for index in cardButtons.indices {
buttons.append(cardButtons[index])
}
for index in cardButtons.indices {
cardButtons[index] = buttons.remove(at: buttons.count.arc4random)
}
}
You could add the buttons to an array, shuffle the array and then loop through it and place the buttons. A better solution would be to create a UICollectionView instead though.

Passing data from view controller to view controller with a delegate

Tried to send data from one view controller (from an alamofire request) to the next view controller in a navigation controller.
I tried to this with a delegate, but I do not get it working. I allready know this is not the way, but i need to find a solution to get it working.
See below for the code, from view controller that sends variabels:
protocol SendDataToScanInfo {
func sendData (vendorname01 : String, productname01: String, productstatus01: String, productdescription01: String)
}
class ScanController: UIViewController, AVCaptureMetadataOutputObjectsDelegate, CLLocationManagerDelegate{
var delegate:SendDataToScanInfo?
func captureOutput(_ captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [Any]!, from connection: AVCaptureConnection!) {
Alamofire.request(URL_SCAN_ID, method: .post, parameters: ScanParameters, encoding: JSONEncoding.default) .responseJSON
{
response in
//printing response
print(response.request!)
print(response.response!)
print(response.data!)
print(response.result)
print(response.error)
//getting the json value from the server
let value = response.result.value
print(value!)
let json = JSON(value!)
let productdesc0:JSON = json["productdesc"]
let productdescString = productdesc0.string
let productname0:JSON = json["productname"]
let productnameString = productname0.string
let tagstate0:JSON = json["tagstate"]
let tagstateString = tagstate0.string
let vendorname0:JSON = json["vendorname"]
let vendornameString = vendorname0.string
//self.performSegue(withIdentifier: "ScanInfo", sender: productdescString)
self.delegate?.sendData(vendorname01: vendornameString!, productname01: productnameString!, productstatus01: tagstateString!, productdescription01: productdescString!)
print(vendornameString)
}
if code != nil
{
let mainStoryboard = UIStoryboard(name: "Main", bundle: nil)
let destination = mainStoryboard.instantiateViewController(withIdentifier: "ScanInfo")
navigationController?.pushViewController(destination, animated: true)
}
captureSession.stopRunning();
//self.dismiss(animated: true, completion: nil)
}
}
}
Next Viewcontroller should receive it:
class ScanInfoViewController: UIViewController, SendDataToScanInfo {
#IBOutlet weak var Vendor: UILabel!
#IBOutlet weak var VendorScan: UILabel!
#IBOutlet weak var Product: UILabel!
#IBOutlet weak var ProductScan: UILabel!
#IBOutlet weak var Status: UILabel!
#IBOutlet weak var DescriptionScan: UILabel!
#IBOutlet weak var Description: UILabel!
#IBOutlet weak var StatusScan: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
DescriptionScan.text = descriptionBLA
print("jddjd", descriptionBLA)
let URL_SCAN_INFO = "http://makeitrain.get-legit.com:8998/checktag"
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func sendData(vendorname01: String, productname01: String, productstatus01: String, productdescription01: String) {
VendorScan.text = vendorname01
ProductScan.text = productname01
DescriptionScan.text = productdescription01
StatusScan.text = productstatus01
print("MMMM", StatusScan.text)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "ScanInfo" {
let sendingVC: ScanController = segue.destination as! ScanController
sendingVC.delegate = self
}
}
}
I hope some one can help me!
To pass data forward, like williej926 said, segues are the way to go. To pass data forward from one viewcontroller to another, you need to create a segue between these two viewcontrollers, and give the segue an identifier if there is more than one segue in your project that you are using to pass data, then this is a must. In your first view controller's class you should create a prepareForSegue method by using the one built-in. In that prepareForSegue method, you write if the segue's identifier is equal to the one that you have set in your storyboard. In that if statement, you need to tell this viewcontroller what your segue's destination is. To do that write let destination = segue.destination as! nextViewControllerClass. To access variables and set them in your second viewcontroller, write destination.variableName = thisVariableName. Here is an example showing you what this looks like purely in code.
In First View Controller's class
class FirstViewController: UIViewController {
var thisString: String?
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let identifier = segue.identifier {
if(identifier == "secondViewController") {
let destination = segue.destination as! SecondViewController//SecondViewController is second view controller's class
destination.myString = thisString
}
}
}
}
Second View Controller's Class
class SecondViewController: UIViewController {
var myString: String?//this will equal to thisString in FirstViewController
}
I wrote an answer about this not too long ago :
One the simpler way to pass info from one VC to another is either through an initiliazer, or through a variable that you set before presenting the second VC.
The secone method would have you go through a delegate, mainly when passing data BACK to the initial VC. Either way, you'd need a setup similar to this:
class LoggedInVCViewController : UIViewController {
var info : String? {
didSet {
if let newInfo = self.info {
//do what ever you need to do here
}
}
}
override viewDidLoad() {
super.viewDidLoad()
}
}
func presentLoggedInScreen(yourInfo: String) {
let stroyboard:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let loggedInVC:LoggedInVCViewController =
storyboard.instantiateViewController(withIdentifier: "loggedInVC") as!
LoggedInVCViewController
loggedInVC.info = yourInfo
self.present(loggedInVC, animated: true, completion: nil)
}
class LoggedInVCViewController : UIViewController {
var info : Any? {
get {
if let this = self.info {
return this
} else {
return nil
}
} set {
if let new = newValue {
//
}
}
}
init(info: Any?) {
//This first line is key, it also calls viewDidLoad() internally, so don't re-write viewDidLoad() here!!
super.init(nibName: nil, bundle: nil)
if let newInfo = info {
//here we check info for whatever you pass to it
self.info = newInfo
}
}
override func viewDidLoad() {
super.viewDidLoad()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
Which is then used :
func presentLoggedInScreen(yourInfo: String) {
let loggedInVC = LoggedInVCViewController(info: yourInfo)
self.present(loggedInVC, animated: true, completion: nil)
}
Or if you're using the variable approach:
func presentLoggedInScreen(yourInfo: String) {
let loggedInVC = LoggedInVCViewController()
loggedInVC.info = yourInfo
self.present(loggedInVC, animated: true, completion: nil)
}
I also go over, and link to other post which talk about the caveats of using Storyboards, and custom initializers to pass on data. I'd read over them as well!
The best way to do this is by using a segue. Connect a segue between the controllers and in the prepareForSegue you add a variable that represents the controller you are segueing to like so: let viewController = segue.destination as! viewController. Now you can access and change variables inside viewController using viewController.variable.

How to make a timer reset after button gesture in a different view controller?

I am developing a quiz app where the user is asked a question at random and must answer it on the initial view controller. If the user picks correctly, a second view controller appears which contains a button that pops the view controller off the navigation stack and goes back to the initial view controller to finish the other questions. However, I have a timer that I want to reset (start at 15s) every time that second view controller is popped and the initial view controller appears with the next question. How would I accomplish this task? I already have the countdown timer code in my swift file. I just need to know how to get it to start from scratch every time the second view controller is popped/removed.
Here's my code for the initial view controller:
import UIKit
extension ViewController: QuizCompletedDelegate {
func continueQuiz() {
randomQuestion()
}
}
class ViewController: UIViewController {
var questionList = [String]()
func updateCounter() {
counter -= 1
questionTimer.text = String(counter)
if counter == 0 {
timer.invalidate()
wrongSeg()
counter = 15
}
}
func randomQuestion() {
//random question
if questionList.isEmpty {
questionList = Array(QADictionary.keys)
}
let rand = Int(arc4random_uniform(UInt32(questionList.count)))
questionLabel.text = questionList[rand]
//matching answer values to go with question keys
var choices = QADictionary[questionList[rand]]!
questionList.remove(at: rand)
//create button
var button:UIButton = UIButton()
//variables
var x = 1
rightAnswerBox = arc4random_uniform(4)+1
for index in 1...4 {
button = view.viewWithTag(index) as! UIButton
if (index == Int(rightAnswerBox)) {
button.setTitle(choices[0], for: .normal)
} else {
button.setTitle(choices[x], for: .normal)
x += 1
}
randomImage()
}
}
let QADictionary = ["Who is Thor's brother?" : ["Atum", "Loki", "Red Norvell", "Kevin Masterson"], "What is the name of Thor's hammer?" : ["Mjolinr", "Uru", "Stormbreaker", "Thundara"], "Who is the father of Thor?" : ["Odin", "Sif", "Heimdall", "Balder"]]
//wrong view segue
func wrongSeg() {
performSegue(withIdentifier: "incorrectSeg", sender: self)
}
//proceed screen
func rightSeg() {
performSegue(withIdentifier: "correctSeg", sender: self)
}
//variables
var rightAnswerBox:UInt32 = 0
var index = 0
//Question Label
#IBOutlet weak var questionLabel: UILabel!
//Answer Button
#IBAction func buttonAction(_ sender: AnyObject) {
if (sender.tag == Int(rightAnswerBox)) {
rightSeg()
print ("Correct!")
}
if counter != 0 {
counter = 15
questionTimer.text = String(counter)
} else if (sender.tag != Int(rightAnswerBox)) {
wrongSeg()
print ("Wrong!")
timer.invalidate()
questionList = []
}
}
override func viewDidAppear(_ animated: Bool) {
randomQuestion()
}
//variables
var counter = 15
var timer = Timer()
#IBOutlet weak var questionTimer: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
timer = Timer.scheduledTimer(timeInterval: 1, target:self, selector: #selector(ViewController.updateCounter), userInfo: nil, repeats: true)
}
}
Here's the code to the second view controller:
class ContinueScreen: UIViewController {
var delegate: QuizCompletedDelegate?
//correct answer label
#IBOutlet weak var correctLbl: UILabel!
//background photo
#IBOutlet weak var backgroundImage: UIImageView!
func backToQuiz() {
delegate?.continueQuiz()
if let nav = self.navigationController {
nav.popViewController(animated: true)
} else {
self.dismiss(animated: true, completion: nil)
}
}
#IBAction func `continue`(_ sender: Any) {
backToQuiz()
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
How to make countdown timer reset after button push on different view
controller?
So if you can get the reference of yourView controller where you have
setup the timer then you can access counter variable from previous
view controller inside your second viewController and when pushed the
button just reset to 0.
If above approach is not possible for you then another way is create
the static variable and access it anywhere and reset like this:-
static var counter = 0
if you are popping/removing the 2nd view controller and thus returning to the first, you could reset the timer in your viewDidAppearfunc in your 1st view controller. this way the timer restarts every time the view appears - the first time, and whenever the 2nd pops.

How to set up a NSComboBox using prepare for segue or init?

I am really struggling to pass the contents of one array from a view controller to another to set up the contents of a nscombobox. I have tried everything I can think of, prepare for segue, init; but nothing seems to work.
the program flow is as follows: the user enter a number into a text field and based on it an array with the size of the number is created. Once the user presses a button the next VC appears that has a combo box and inside that combo box those numbers need to appear. All my attempts result in an empty array being passed. Could someone please take a bit of time and help me out. Im sure I'm doing a silly mistake but cannot figure out what.
Code listing below:
Class that take the user input. At this stage I'm trying to pass the contents of the array in the next class as I gave up on prepare for segue because that one crashes because of nil error. Please note that prepare for segue is uncommented in the code listing just for formatting purposes here. Im my program it is commented out as I am using perform segue at the moment.
Any solution would be nice please. Thank you.
import Cocoa
class SetNumberOfFloorsVC: NSViewController {
//MARK: - Properties
#IBOutlet internal weak var declaredNumber: NSTextField!
internal var declaredFloorsArray = [String]()
private var floorValue: Int {
get {
return Int(declaredNumber.stringValue)!
}
}
//MARK: - Actions
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction private func setNumberOfFloors(_ sender: NSButton) {
if declaredNumber.stringValue.isEmpty {
let screenAlert = NSAlert.init()
screenAlert.messageText = "Please specify the number of floors!"
screenAlert.addButton(withTitle: "Got it!")
screenAlert.runModal()
} else if floorValue == 0 || floorValue < 0 {
let screenAlert = NSAlert.init()
screenAlert.messageText = "Please input a correct number of floors!"
screenAlert.addButton(withTitle: "Got it!")
screenAlert.runModal()
} else {
for i in 0...floorValue - 1 {
declaredFloorsArray.append(String(i))
}
print("\(declaredFloorsArray)")
let declareNumberOfRoomsVC = SetNumberOfRoomsForFloorVC(boxData: declaredFloorsArray)
declareNumberOfRoomsVC.boxData = declaredFloorsArray
performSegue(withIdentifier: "set number of rooms", sender: self)
}
}
override func prepare(for segue: NSStoryboardSegue, sender: Any?) {
if segue.identifier == "set number of rooms" {
if let addRoomsVC = segue.destinationController as? SetNumberOfRoomsForFloorVC {
addRoomsVC.floorBox.addItems(withObjectValues: declaredFloorsArray)
}
}
}
}
this is the class for the next VC with the combo box:
import Cocoa
class SetNumberOfRoomsForFloorVC: NSViewController, NSComboBoxDelegate, NSComboBoxDataSource {
//MARK: - Properties
#IBOutlet internal weak var floorBox: NSComboBox!
#IBOutlet private weak var numberOfRoomsTxtField: NSTextField!
internal var boxData = [String]()
//MARK: - Init
convenience init(boxData: [String]) {
self.init()
self.boxData = boxData
}
//MARK: - Actions
override func viewDidLoad() {
super.viewDidLoad()
floorBox.usesDataSource = true
floorBox.dataSource = self
floorBox.delegate = self
print("\(boxData)")
}
#IBAction private func setRoomsForFloor(_ sender: NSButton) {
}
//MARK: - Delegates
func numberOfItems(in comboBox: NSComboBox) -> Int {
return boxData.count
}
func comboBox(_ comboBox: NSComboBox, objectValueForItemAt index: Int) -> Any? {
return boxData[index]
}
}
First you should remove the following code.
let declareNumberOfRoomsVC = SetNumberOfRoomsForFloorVC(boxData: declaredFloorsArray)
declareNumberOfRoomsVC.boxData = declaredFloorsArray
I assume you think that the viewController you created here is passed to prepareForSegue. However the storyboard instantiates a new viewController for you.
After that you need to set your declaredFloorsArray as the the boxData of the new viewController in prepareForSegue and you should be good to go.