reset variables when pass to an another ViewController - ios

my problem is that when i switch to an another ViewController, my variables of the previous VC call are reset so i can't do what i want after
#IBAction func BackBtn(_ sender: Any) {
self.nbrQst = 10
self.Switch1A = 2
performSegue(withIdentifier: "Numero", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "Numero" {
let vc = segue.destination as! ViewController
vc.nbrQt = nbrQst
}
if segue.identifier == "Numero" {
let vcNv = segue.destination as! ViewController
vcNv.Switch1 = Switch1A
}
}
below the way that i send information from my Lvl1 file to the lvl selector file to add a if else for unblocks the lvl
#IBAction func BackBtn(_ sender: Any) {
self.nbrQst = 10
self.Switch1A = 2
performSegue(withIdentifier: "Numero", sender: self)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let vc = segue.destination as! ViewController
vc.nbrQt = nbrQst
vc.Switch1 += 2
}
that's the second ViewController who send the number to the first one, and i want that the first one remember the number and add them up each time I press the button that sends the numbers

Let's call "Selector VC" the main VC.
The reason why those numbers reset in main VC is that when you press the "BackBtn", you're not actually going back to main VC, you're creating a new main VC and going there (because you did performSegue(withIdentifier: "Numero", sender: self) in BackBtn function, performSegue always takes you to a new VC rather than taking you back). The new main VC has all those fields starting from an initial number (I assume initially they're zero).
What you want to do is to go BACK, not forward. Depending on how you went to the level VC from main VC, you have different ways of going back to main VC.
If you're pushing everything onto a navigation controller, then you can go back by:
self.navigationController?.popToRootViewController(animated: true)
If you're presenting everything modally, you can go back by
self.dismiss(animated: true, completion: nil)
You said, you want to update the value in main VC so that you can block/unblock next level. A very standard way to achieve this is via delegate, please Google this ("delegates in Swift") and follow their tutorials there.
I strongly recommend that you take an online course on swift development before you go ahead and develop your own app, because you could potentially do a lot of things wrong and waste a lot of your time trying to get an answer from Stack Overflow.

Related

navigation bar disappear after adding prepare function

I am woking on an recording APP.
I tried to add navigation controller in my first recording viewcontroller which then could pass filename array to the second viewcontroller using the following function prepare:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let controller = segue.destination as? MainViewController
controller?.recordArray = recordingArray
self.present(controller!, animated: true, completion: nil)
}
However, when ran in the simulator the navigation bar disappeared in the second controller and Xcode pops out the warning
Thread1: EXC_BAD_ACCESS(code=2,address=0x7fff51edfff8)
Has anyone got any advice?
Thanks!
Don't ever call present(_:animated:completion:) inside prepare(for segue:).
prepare(for segue) is called automatically by the system just before a segue is about to happen to let you prepare the data for sending to the destination viewcontroller or do any other calculations you need to before performing the segue. A segue needs to be set up in Storyboard and it will either be called automatically or if it is a manual segue, you need to call it using perform(segue) and once you do that, the system will call prepare(for segue) for you. You can see why calling another navigation function proves to be problematic, since you are trying to navigate to another viewcontroller using two different methods (segue and present).
If you haven't set up the segue in Storyboard, then you also need to do that, since if it is not set up, let controller = segue.destination as? MainViewController will be nil.
Once you set up the segue in Storyboard, this is how your function should look like:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let controller = segue.destination as? MainViewController {
controller.recordArray = recordingArray
self.present(controller, animated: true, completion: nil)
}
}
You shouldn’t be trying to present a VC in this method, it’s just a place for you to configure the destination VC before the segue presents it
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let controller = segue.destination as? MainViewController else { return }
controller.recordArray = recordingArray
}

iOS Swift - Data is not fetched quickly enough to reach another UIViewController

I have a source view controller and a destination view controller.
I would like to show data fetched from a url in the UI (destination) just after moving to this screen ("show" segue).
In order to do that, in the source VC I use "prepare for segue" method, where I call a function that returns an array with all the fetched data I want to show and pass it to the destination VC to be shown in a UITableView.
The problem is that many times the whole data is not fetched from the url, so I pass an empty array to the destination.
This is the code in the source VC:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destinationVc = segue.destination as?
ShowCharacterInfoViewController{
fetchCharacterArrayFromUrl(characterName: cellContent){ results in
destinationVc.array.append(contentsOf:results)
destinationVc.tabelView.reloadData()}
} }
I can't think of a proper solution.
You can do one of two things.
Load the data and only perform the segue after the function has returned the data.
Transition to the destination screen and have that controller load the data in viewWillAppear.
// Add a place to save the results
var saveResults: MyResultsType?
#IBAction func someButtonAction(_ sender: Any) {
// Consider putting a "Loading..." dialog here
fetchCharacterArrayFromUrl(characterName: cellContent){ results in
self.saveResults = results
DispatchQueue.main.async({
// Hide the "Loading..." dialog
performSegue(withIdentifier: "ID of your Segue", sender: sender) //
})
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destinationVc = segue.destination as? ShowCharacterInfoViewController {
// I'm not sure append() is really what you need here
destinationVc.array.append(contentsOf: savedResults)
destinationVc.tabelView.reloadData()
}
}
You need to update the UI stuff in main thread since you are executing backend call:-
DispatchQueue.main.async({
destinationVc.tabelView.reloadData()
})

Performing segue after sender view controller is dismissed

Basically, I have a button in a slide-out menu (which is its own view controller that covers part of the Origin screen, let's call it Menu) that, when pressed, performs a modal segue to another controller, let's say Destination.
Is there any way that upon pressing the button in Menu (to go to Destination), that I can dismiss Menu back to Origin, and THEN segue to Destination?
It sounds silly but it's something that I think I've seen apps do before. In my case, the reason for wanting to do this is that once I press "Done" on Destination, it dismisses that controller back to Menu, when I want it to just dismiss back to Origin. I can't just perform a segue back to Origin from Destination.
Code:
This is how I open the Menu from Origin:
let interactor = Interactor()
#IBAction func openMenu(_ sender: AnyObject) {
performSegue(withIdentifier: "openMenu", sender: nil)
}
#IBAction func edgePanGesture(sender: UIScreenEdgePanGestureRecognizer) {
let translation = sender.translation(in: view)
let progress = MenuHelper.calculateProgress(translationInView: translation, viewBounds: view.bounds, direction: .Right)
MenuHelper.mapGestureStateToInteractor(
gestureState: sender.state,
progress: progress,
interactor: interactor){
self.performSegue(withIdentifier: "openMenu", sender: nil)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destinationViewController = segue.destination as? MenuViewController {
destinationViewController.transitioningDelegate = self
destinationViewController.interactor = interactor
destinationViewController.currentRoomID = self.currentRoomID
}
}
This is my prepareForSegue from Menu to Destination currently, nothing fancy:
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
super.prepare(for: segue, sender: sender)
let inviteVC = segue.destination as! InviteVipViewController
inviteVC.currentRoomID = self.currentRoomID
}
And finally to dismiss Destination is just a simple
#IBAction func cancelButtonPressed(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
I saw this question which is basically what I'm trying to do but there was no answer unfortunately: Performing segue after dismissing modal swift
Sorry if this sounds confusing, but if anyone knows what I'm talking about and can let me know how I can set up the segues/prepareForSegues to make it work, any input would be appreciated!
Based on a modification to this answer, the following should work:
In your storyboard, remove the segue that is triggered by tapping your menu button and goes to Destination.
Create a new segue that goes from the Origin view controller to Destination view controller. This segue is going to be manually performed.
When your Destination option is selected in Menu, have Menu dismiss itself and then perform the Destination segue on Origin, like this:
// This code goes in Menu, and you should call it when
// the menu button is tapped.
//
// presentingViewController is Origin
weak var pvc = self.presentingViewController
self.dismiss(animated: true) {
// Menu has been dismissed, but before it is destroyed
// it calls performSegue on Origin
pvc?.performSegue(withIdentifier: "openDestination", sender: nil)
}
When Destination is dismissed, you should see Origin, without seeing Menu at all.
I tested this in a sample app where "Menu" was not a slide out, but a full modal view controller, and it worked for me.
EDIT: While troubleshooting with #KingTim, he found that we needed to wire the segue from the UINavigationController, not Origin, to the Destination. This is because Origin is inside a navigation controller. After that discovery, it worked.
If your presenting view is embedded in a navigation controller then you can do this:
weak var pvc:UIViewController! = self.presentingViewController?.childViewControllers[0]
dismiss(animated: true)
{
pvc.performSegue(withIdentifier: "SegueID", sender: nil)
}
Simple solution with presentingViewController
if let destinationVC = self.presentingViewController as? YourViewController {
destinationVC.isBooleanPassed = true
destinationVC.selectedString = "here comes your string"
destinationVC.selectedInteger = 12345
}
dismiss(animated: true, completion: nil)

Restore View State with segue ios

I have setting like this:
First controller reads data and sets in Second Controller.
Second Controller has a button that executes push segue to Third Controller with a countdown.
After countdown I want to go back from third controller to second that should still have data. Is there any way to achieve this?
Also I am using Storyboards.
I send data to Second Controller in prepare func. Second to Third controller change is connected directly to button in Storyboards.
override func prepare(for segue: UIStoryboardSegue, sender: AnyObject?) {
let controller = segue.destination as! QuestionViewController
controller.questionIDs = sender as! [Int]
}
To come back from Third to Second controller I use this code from Third controller:
self.performSegue(withIdentifier: "nobodyAnsweredSegue", sender: self)
Change this:
self.performSegue(withIdentifier: "nobodyAnsweredSegue", sender: self)
To this:
self.navigationController?.popViewControllerAnimated(true)

segue.destinationVC is nil in prepareForSegue

I've looked around many threads and haven't benefitted with my issue. My issue lies in my 3rd VC where the user taps an 'Edit UIBarButtonItem' which segues them to the 4th VC. The segue ID is correct and both VC's 3 and 4 are static table VC's, but 4 is embedded in a nav controller and 3 isn't. i want the data in the textfields in VC 3 to be 'copied' to the almost identical looking textfields in VC 4, so that changes can be made by the user and updated. When i type cast my destination segue as the 4th VC inside prepareForSegue, it returns nil and the instance of data inside doesn't get moved to the 4th VC since 'if let' is being used. Why does it return nil? I've looked up the life cycle of segues too but haven't learnt much, all other VC's are fine.
I have tried both below and both return nil for VC 4
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "EditSegue" {
print("correct segue name")
if let editVC: EditTableViewController = segue.destinationViewController as? EditTableViewController {
editVC.instanceOfData = self.instanceOfData //instance of data in 4th VC = instanceOfData in 3rd VC
}
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let editVC = segue.destinationViewController as? EditTableViewController
if segue.identifier == "EditSegue" {
editVC.instanceOfData = self.instanceOfData
}
}
I could be doing something obviously wrong which i haven't come across yet! I've successfully transferred data between two VC's before but not when instances have been passed around between VC's.
Any help is appreciated, thanks.

Resources