Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 616 Vote(s) - 3.42 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Passing data between view controllers

#31
# Swift

There are tons and tons of explanations here and around Stack Overflow, but if you are a beginner just trying to get something basic to work, try watching this YouTube tutorial (It's what helped me to finally understand how to do it).

- YouTube tutorial: *[How to send data through segue (Swift)][1]*

# Passing data forward to the next View Controller

The following is an example based on the video. The idea is to pass a string from the text field in the First View Controller to the label in the Second View Controller.

[![Enter image description here][2]][2]

Create the storyboard layout in the Interface Builder. To make the segue, you just <kbd>Control</kbd> click on the button and drag over to the Second View Controller.

**First View Controller**

The code for the First View Controller is

import UIKit

class FirstViewController: UIViewController {

@IBOutlet weak var textField: UITextField!

// This function is called before the segue
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

// Get a reference to the second view controller
let secondViewController = segue.destination as! SecondViewController

// Set a variable in the second view controller with the String to pass
secondViewController.receivedString = textField.text!
}

}

**Second View Controller**

And the code for the Second View Controller is

import UIKit

class SecondViewController: UIViewController {

@IBOutlet weak var label: UILabel!

// This variable will hold the data being passed from the First View Controller
var receivedString = ""

override func viewDidLoad() {
super.viewDidLoad()

// Used the text from the First View Controller to set the label
label.text = receivedString
}

}

**Don't forget**

- Hook up the outlets for the `UITextField` and the `UILabel`.
- Set the first and second View Controllers to the appropriate Swift files in [Interface Builder][3].

# Passing data back to the previous View Controller

To pass data back from the second view controller to the first view controller, you use [a protocol and a delegate][4]. This video is a very clear walk though of that process:

- YouTube tutorial: [iOS Swift Basics Tutorial: Protocols and Delegates][5] But also read [this post][6] to make sure you don't get into a strong reference cycle.

The following is an example based on the video (with a few modifications).

[![Enter image description here][7]][7]

Create the storyboard layout in the Interface Builder. Again, to make the segue, you just <kbd>Control</kbd> drag from the button to the Second View Controller. Set the segue identifier to `showSecondViewController`. Also, don't forget to hook up the outlets and actions using the names in the following code.

**First View Controller**

The code for the First View Controller is

import UIKit

class FirstViewController: UIViewController, DataEnteredDelegate {

@IBOutlet weak var label: UILabel!

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showSecondViewController" {
let secondViewController = segue.destination as! SecondViewController
secondViewController.delegate = self
}
}

func userDidEnterInformation(info: String) {
label.text = info
}
}

Note the use of our custom `DataEnteredDelegate` protocol.

**Second View Controller and Protocol**

The code for the second view controller is

import UIKit

// Protocol used for sending data back
protocol DataEnteredDelegate: AnyObject {
func userDidEnterInformation(info: String)
}

class SecondViewController: UIViewController {

// Making this a weak variable, so that it won't create a strong reference cycle
weak var delegate: DataEnteredDelegate? = nil

@IBOutlet weak var textField: UITextField!

@IBAction func sendTextBackButton(sender: AnyObject) {

// Call this method on whichever class implements our delegate protocol
delegate?.userDidEnterInformation(info: textField.text!)

// Go back to the previous view controller
_ = self.navigationController?.popViewController(animated: true)
}
}

Note that the `protocol` is outside of the View Controller class.

That's it. Running the app now, you should be able to send data back from the second view controller to the first.

[1]:
[2]:

[3]:

[To see links please register here]

[4]:

[To see links please register here]

[5]:
[6]:

[To see links please register here]

[7]:

Reply

#32
With a *Swift* slant and want a bare-bones example, here is my go-to method for passing data if you are using a segue to get around.

It is similar to the above but without the buttons, labels and such. Just simply passing data from one view to the next.

**Setup The Storyboard**

There are three parts.

1. The Sender
2. The Segue
3. The Receiver

This is a very simple view layout with a segue between them.

----------

[![Very simple view layout. Note: No navigation controller][1]][1]

----------

Here is the setup for the sender

----------

[![The Sender][2]][2]

----------

Here is the setup for the receiver.

----------

[![The Receiver][3]][3]

----------

Lastly, the setup for the segue.

----------

[![The Segue Identifier][4]][4]

----------

**The View Controllers**

We are keeping this simple so no buttons and not actions. We are simply moving data from the sender to the receiver when the application loads and then outputting the transmitted value to the console.

This page takes the initially loaded value and passes it along.

import UIKit


class ViewControllerSender: UIViewController {

// THE STUFF - put some information into a variable
let favoriteMovie = "Ghost Busters"

override func viewDidAppear(animated: Bool) {
// PASS IDENTIFIER - go to the receiving view controller.
self.performSegueWithIdentifier("goToReciever", sender: self)
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

// GET REFERENCE - ...to the receiver view.
var viewControllerReceiver = segue.destinationViewController as? ViewControllerReceiver

// PASS STUFF - pass the variable along to the target.
viewControllerReceiver!.yourFavMovie = self.favoriteMovie

}
}

This page just sends the value of the variable to the console when it loads. By this point, our favorite movie should be in that variable.

import UIKit

class ViewControllerReceiver: UIViewController {

// Basic empty variable waiting for you to pass in your fantastic favorite movie.
var yourFavMovie = ""

override func viewDidLoad() {
super.viewDidLoad()

// And now we can view it in the console.
println("The Movie is \(self.yourFavMovie)")

}
}

That is how you can tackle it if you want to use a segue and you don't have your pages under a navigation controller.

Once it is run, it should switch to the receiver view automatically and pass the value from the sender to the receiver, displaying the value in the console.

[![Ghost Busters is a classic folks.][5]][5]

[1]:

[2]:

[3]:

[4]:

[5]:



Reply

#33
This is [a really great tutorial][1] for anyone that wants one. Here is the example code:

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([segue.identifier isEqualToString:@"myIdentifer]) {
NSIndexPath *indexPath = [self.tableView indexPathForSelectedRow];
myViewController *destViewController = segue.destinationViewController;
destViewController.name = [object objectAtIndex:indexPath.row];
}
}

[1]:

[To see links please register here]

Reply

#34
To send the data from one view controller (VC) to the other, use this simple approach:

YourNextVC *nxtScr = (YourNextVC*)[self.storyboard instantiateViewControllerWithIdentifier:@"YourNextVC"];//Set this identifier from your storyboard

nxtScr.comingFrom = @"PreviousScreen"l
[self.navigationController nxtScr animated:YES];

Reply

#35
An Apple way to do this is to use Segues. You need to use the prepareForSegue() function.

There are lots of great tutorials around, and here is one:
*[Unleash Your Inner App Developer Part 21: Passing Data Between Controllers][1]*

Also, read up the Apple documentation on using segues:
*[Using Segues][2]*

[1]:

[To see links please register here]

[2]:

[To see links please register here]





Reply

#36
You have to always follow the MVC concept when creating apps for iOS.

There are two scenarios where you may want to pass data from a ViewController to another:

1. When there is an "A" ViewContoller in the hierarchy and you want to send some data to "B" which is the **next** viewcontroller. In this case you have to use Segue. Just set an identifier for the segue and then in the "A" VC, write the following code:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "A to B segue identifier" {
let bViewController = segue.destination as! UIDocumentBrowserViewController
bViewController.data = someData
}
}

2. When there is an `A` which opened `B` upon itself as modal (or embed). Now the `B` viewcontroller should be blind about its parent. So the best way to send data back to `A` is to use `Delegation`.

Create a delegate protocol in the `B` viewcontroller and a `delegate` property. So `B` will report (send data back) to it's delegate. In the `A` viewcontroller, we implement the `B` viewcontroller's delegate protocol and will set `self` as the `delegate` property of `B` viewcontroller in `prepare(forSegue:)` method.

This is how it should be implemented correctly.

Reply

#37
You can create a push segue from the source viewcontroller to the destination viewcontroller and give an identifier name like below.

[![Enter image description here][1]][1]

You have to perform a segue from didselectRowAt like this.

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
performSegue(withIdentifier: "segue", sender: self)
}

And you can pass the array of the selected item from the below function.

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let index = CategorytableView.indexPathForSelectedRow
let indexNumber = index?.row
print(indexNumber!)
let VC = segue.destination as! AddTransactionVC
VC.val = CategoryData[indexNumber!] . // Here you can pass the entire array instead of an array element.
}

And you have to check the value in viewdidload of destination viewcontroller and then store it into the database.

override func viewDidLoad{
if val != ""{
btnSelectCategory.setTitle(val, for: .normal)
}
}

[1]:


Reply

#38
Well, we have a few ways we can work with the delegates system or using storyboardSegue:

1. As working with setter and getter methods, like in viewController.h

@property (retain, nonatomic) NSString *str;

Now, in viewController.m

@synthesize str;

Here I have a PDF URL and a segue to another viewController like this and pdfObject is my pdfModel. It is basically an NSOBJECT class.

str = [NSString stringWithFormat:@"%@", pdfObject.objPath];
NSLog(@"pdfUrl :***: %@ :***:", pdfUrl);

[self performSegueWithIdentifier:@"programPDFViewController_segue" sender:self];

#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {

if ([[segue identifier] isEqualToString:@"programPDFViewController_segue"]) {
programPDFViewController *pdfVC = [segue destinationViewController];
[pdfVC setRecievedPdfUrl:str];
}
}

Now successfully I received my PDF URL string and other ViewController and use that string in webview...

2. As working with delegates like this I have one NSObject class of utilities containing my methods of dateFormatter, sharedInstance, EscapeWhiteSpaceCharacters, convertImageToGrayScale and more method I worked with throughout the application so now in file *utilities.h*.

In this, you don’t need to create variables every time parsing data from one to another view controller. One time, you create a string variable in file *utilities.h*.

Just make it `nil` and use it again.

@interface Utilities : NSObject

File *Utilities.h*:

+(Utilities*)sharedInstance;

@property(nonatomic, retain)NSString* strUrl;

Now in file *utilities.m*:

@implementation utilities

+(utilities*)sharedInstance
{
static utilities* sharedObj = nil;
if (sharedObj == nil) {
sharedObj = [[utilities alloc] init];
}
return sharedObj;
}

Now it's done, come to your file *firstViewController.m* and call the delegate

NSString*str = [NSString stringWithFormat:@"%@", pdfObject.objPath];

[Connection sharedInstance].strUrl = nil;
[Connection sharedInstance].strUrl = str;

Now go to you file *secondViewController.m* directly, and use it without creating a variable

In viewwillapear what I did:

-(void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:YES];

[self webViewMethod:[Connection sharedInstance].strUrl];
}


-(void)WebViewMethod:(NSString)Url {

// Working with webview. Enjoy coding :D
}

This delegate work is reliable with memory management.






Reply

#39
## Using Notification Center

For Swift 3
-----------


let imageDataDict:[String: UIImage] = ["image": image]

// Post a notification
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict)
// `default` is now a property, not a method call

// Register to receive notification in your class
NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)

// Handle notification
func showSpinningWheel(_ notification: NSNotification) {
print(notification.userInfo ?? "")
if let dict = notification.userInfo as NSDictionary? {
if let id = dict["image"] as? UIImage {
// Do something with your image
}
}
}


For Swift 4
-----------

let imageDataDict:[String: UIImage] = ["image": image]

// Post a notification
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict)
// `default` is now a property, not a method call

// Register to receive notification in your class
NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)

// Handle notification
@objc func showSpinningWheel(_ notification: NSNotification) {
print(notification.userInfo ?? "")
if let dict = notification.userInfo as NSDictionary? {
if let id = dict["image"] as? UIImage {
// Do something with your image
}
}
}

Reply

#40
There are many solutions for passing data in **Swift**.

**Passing data forward**

My two favorite ways to pass data forwardly is [dependency injection][1] (DI) and Property Observers


**Dependency Injection**

class CustomView : UIView {
init(_ with model : Model) {
// Do what you want with data
}
}


**Property Observers**

class CustomView : UIView {
var model : Model? {
didSet {
// Do what you want with data after assign data to model
}
willSet {
// Do what you want with data before assign data to model
}
}
}

**Passing data backward**

Also favorite ways to *passing* data to the previous VC/view:

**Protocol and Delegate**

protocol CustomViewDelegate : class {
func addItemViewController(_ with data: Model?)
}

weak var delegate : CustomViewDelegate?

class AnotherCustomView: UIView {

let customView = AnotherCustomView()

init() {
customView.delegate = self
}
}

extention AnotherCustomView : CustomViewDelegate {
func addItemViewController(_ with data: Model?) {
// Do what you want with data
}
}


**Closure**

class AnotherCustomView : UIView {
init(addItem: @escaping (_ value : Model?) -> ()) {
// Do what you want with data
}
}

class CustomView : UIView {

init() {
let customView = AnotherCustomView { [weak self] model in
// Do what you want with data
}
}
}

[1]:

[To see links please register here]


Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through