How to pass Item from initial (one time) first time view controller to main view controller and save that...












1















I have been working on this issue for two days now and sadly I cannot figure out the issue to my problem. I'm trying to take one item from my initial one time view controller and send that to my main view controller where it will be saved within the main view controller and will appear upon that controller when reloading the app.



Here is my app delegate code for the "first time" view controller



 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

if UserDefaults.standard.bool(forKey: "firstTimer") {
let storyBoard = UIStoryboard.init(name: "Main", bundle: nil)
let mainView = storyBoard.instantiateViewController(withIdentifier: "MainViewControllerID")
let nav = UINavigationController(rootViewController: mainView)
nav.navigationBar.isHidden = true
self.window?.rootViewController = nav
}
return true
}


containers and saveContext are default



import UIKit

import CoreData

class FirstTimeViewController: UIViewController {

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
private var appDelegate = UIApplication.shared.delegate as! AppDelegate
private var player = [Player]()





@IBOutlet weak var nameTextField: UITextField!

override func viewDidLoad() {
super.viewDidLoad()

// Do any additional setup after loading the view.
}

// This View Controller will only be used once upon the first time the app is being used.

// MARK: Make func that prepares for segue on initial opening of app


override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toMainViewController" {
let mainViewController = segue.destination as! UINavigationController
let destination = mainViewController.topViewController as! MainViewController
if let newPlayer = self.nameTextField.text{
destination.name.name = newPlayer
destination.playerData.name = newPlayer
saveItems()
}
}

}

@IBAction func continueButtonPressed(_ sender: UIStoryboardSegue) {
UserDefaults.standard.set(true, forKey: "firstTimer")
let mainPlayer = PlayerData()
let player1 = Player(entity: Player.entity(), insertInto: context)
player1.name = mainPlayer.name
performSegue(withIdentifier: "toMainViewController", sender: self)
saveItems()
}


func saveItems() {
do {
try context.save()
print("File Successfully saved!")
}catch {
print("Error saving Context (error)")
}
}



// MARK: Function to Save and Load data??
/*
// 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.
}
*/

func loadItems() {
let request = Player.fetchRequest() as NSFetchRequest<Player>
do {
player = try context.fetch(request)
print("Info loaded")
} catch {
print("Error fetching data from context (error)")
}
}
}


MainViewController being sent the information. I only want to send one item and save it to that main view controller.



import UIKit
import Foundation
import CoreData

class MainViewController: UIViewController {
//set up model object, buttons, and labels
// let player: Player!
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
private var appDelegate = UIApplication.shared.delegate as! AppDelegate
// lazy var nameText = Player(context: context)
// var playerInfo = [Player]()
lazy var player = [Player]()
let playerData = PlayerData()
var name = ""


@IBOutlet weak var playerName: UILabel!

@IBOutlet weak var currentLevel: UILabel!

@IBOutlet weak var xpCounter: UILabel!

@IBOutlet weak var playerProfileImage: UIImageView!



override func viewDidLoad() {
super.viewDidLoad()

// loadItems()
// name = playerData.name
if let nameOfPlayer = name.name {
print("This is what we see: (nameOfPlayer)")
playerName.text = nameOfPlayer
}
appDelegate.saveContext()

}

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// loadView()

}

@IBAction func menuButtonPressed(_ sender: Any) {

}

func loadItems() {
let request = Player.fetchRequest() as NSFetchRequest<Player>
do {
player = try context.fetch(request)
print("Info loaded")
} catch {
print("Error fetching data from context (error)")
}
}
// MARK : Add Name to Main View


// MARK : Add Xp To Main View

// MARK : Add UI Image to profile image view

// MARK: (Optional) Create a 'Choose a task button to segue to the task tab'


// MARK: Program the Progress Bar to update on xp gained and reset on level up


// MARK: Function to Save and Load data??
}


If dataSource code needed I will add upon request.



Thanks!










share|improve this question

























  • What exactly do you need to pass from your One Time Initial VC to your Main View Controller?

    – Shubham Bakshi
    Nov 14 '18 at 6:31








  • 1





    Is there a reason why you need to send to the main view controller and then store it in core data? I mean could you not store it in core data in the initial view controller itself, and then just access the same value from core data in the main view controller and do what you need to do with it?

    – iOSer
    Nov 14 '18 at 6:38













  • @shubham I made the initial view controller very simple only sending a person's name to the main view controller.

    – Dreaming Savant
    Nov 14 '18 at 6:43











  • @iOSer I wanted to create a one time vc that would pass the person's name to the main view controller. I would like to do what you are suggesting. how would I go about accessing that value once saved?

    – Dreaming Savant
    Nov 14 '18 at 6:46






  • 1





    As @iOSer suggested, you don't need to pass data to another View Controller if the whole point of passing the data is to store it on the other end (like on your Main View Controller). You just save it within your Initial View Controller

    – Shubham Bakshi
    Nov 14 '18 at 6:46
















1















I have been working on this issue for two days now and sadly I cannot figure out the issue to my problem. I'm trying to take one item from my initial one time view controller and send that to my main view controller where it will be saved within the main view controller and will appear upon that controller when reloading the app.



Here is my app delegate code for the "first time" view controller



 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

if UserDefaults.standard.bool(forKey: "firstTimer") {
let storyBoard = UIStoryboard.init(name: "Main", bundle: nil)
let mainView = storyBoard.instantiateViewController(withIdentifier: "MainViewControllerID")
let nav = UINavigationController(rootViewController: mainView)
nav.navigationBar.isHidden = true
self.window?.rootViewController = nav
}
return true
}


containers and saveContext are default



import UIKit

import CoreData

class FirstTimeViewController: UIViewController {

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
private var appDelegate = UIApplication.shared.delegate as! AppDelegate
private var player = [Player]()





@IBOutlet weak var nameTextField: UITextField!

override func viewDidLoad() {
super.viewDidLoad()

// Do any additional setup after loading the view.
}

// This View Controller will only be used once upon the first time the app is being used.

// MARK: Make func that prepares for segue on initial opening of app


override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toMainViewController" {
let mainViewController = segue.destination as! UINavigationController
let destination = mainViewController.topViewController as! MainViewController
if let newPlayer = self.nameTextField.text{
destination.name.name = newPlayer
destination.playerData.name = newPlayer
saveItems()
}
}

}

@IBAction func continueButtonPressed(_ sender: UIStoryboardSegue) {
UserDefaults.standard.set(true, forKey: "firstTimer")
let mainPlayer = PlayerData()
let player1 = Player(entity: Player.entity(), insertInto: context)
player1.name = mainPlayer.name
performSegue(withIdentifier: "toMainViewController", sender: self)
saveItems()
}


func saveItems() {
do {
try context.save()
print("File Successfully saved!")
}catch {
print("Error saving Context (error)")
}
}



// MARK: Function to Save and Load data??
/*
// 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.
}
*/

func loadItems() {
let request = Player.fetchRequest() as NSFetchRequest<Player>
do {
player = try context.fetch(request)
print("Info loaded")
} catch {
print("Error fetching data from context (error)")
}
}
}


MainViewController being sent the information. I only want to send one item and save it to that main view controller.



import UIKit
import Foundation
import CoreData

class MainViewController: UIViewController {
//set up model object, buttons, and labels
// let player: Player!
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
private var appDelegate = UIApplication.shared.delegate as! AppDelegate
// lazy var nameText = Player(context: context)
// var playerInfo = [Player]()
lazy var player = [Player]()
let playerData = PlayerData()
var name = ""


@IBOutlet weak var playerName: UILabel!

@IBOutlet weak var currentLevel: UILabel!

@IBOutlet weak var xpCounter: UILabel!

@IBOutlet weak var playerProfileImage: UIImageView!



override func viewDidLoad() {
super.viewDidLoad()

// loadItems()
// name = playerData.name
if let nameOfPlayer = name.name {
print("This is what we see: (nameOfPlayer)")
playerName.text = nameOfPlayer
}
appDelegate.saveContext()

}

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// loadView()

}

@IBAction func menuButtonPressed(_ sender: Any) {

}

func loadItems() {
let request = Player.fetchRequest() as NSFetchRequest<Player>
do {
player = try context.fetch(request)
print("Info loaded")
} catch {
print("Error fetching data from context (error)")
}
}
// MARK : Add Name to Main View


// MARK : Add Xp To Main View

// MARK : Add UI Image to profile image view

// MARK: (Optional) Create a 'Choose a task button to segue to the task tab'


// MARK: Program the Progress Bar to update on xp gained and reset on level up


// MARK: Function to Save and Load data??
}


If dataSource code needed I will add upon request.



Thanks!










share|improve this question

























  • What exactly do you need to pass from your One Time Initial VC to your Main View Controller?

    – Shubham Bakshi
    Nov 14 '18 at 6:31








  • 1





    Is there a reason why you need to send to the main view controller and then store it in core data? I mean could you not store it in core data in the initial view controller itself, and then just access the same value from core data in the main view controller and do what you need to do with it?

    – iOSer
    Nov 14 '18 at 6:38













  • @shubham I made the initial view controller very simple only sending a person's name to the main view controller.

    – Dreaming Savant
    Nov 14 '18 at 6:43











  • @iOSer I wanted to create a one time vc that would pass the person's name to the main view controller. I would like to do what you are suggesting. how would I go about accessing that value once saved?

    – Dreaming Savant
    Nov 14 '18 at 6:46






  • 1





    As @iOSer suggested, you don't need to pass data to another View Controller if the whole point of passing the data is to store it on the other end (like on your Main View Controller). You just save it within your Initial View Controller

    – Shubham Bakshi
    Nov 14 '18 at 6:46














1












1








1








I have been working on this issue for two days now and sadly I cannot figure out the issue to my problem. I'm trying to take one item from my initial one time view controller and send that to my main view controller where it will be saved within the main view controller and will appear upon that controller when reloading the app.



Here is my app delegate code for the "first time" view controller



 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

if UserDefaults.standard.bool(forKey: "firstTimer") {
let storyBoard = UIStoryboard.init(name: "Main", bundle: nil)
let mainView = storyBoard.instantiateViewController(withIdentifier: "MainViewControllerID")
let nav = UINavigationController(rootViewController: mainView)
nav.navigationBar.isHidden = true
self.window?.rootViewController = nav
}
return true
}


containers and saveContext are default



import UIKit

import CoreData

class FirstTimeViewController: UIViewController {

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
private var appDelegate = UIApplication.shared.delegate as! AppDelegate
private var player = [Player]()





@IBOutlet weak var nameTextField: UITextField!

override func viewDidLoad() {
super.viewDidLoad()

// Do any additional setup after loading the view.
}

// This View Controller will only be used once upon the first time the app is being used.

// MARK: Make func that prepares for segue on initial opening of app


override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toMainViewController" {
let mainViewController = segue.destination as! UINavigationController
let destination = mainViewController.topViewController as! MainViewController
if let newPlayer = self.nameTextField.text{
destination.name.name = newPlayer
destination.playerData.name = newPlayer
saveItems()
}
}

}

@IBAction func continueButtonPressed(_ sender: UIStoryboardSegue) {
UserDefaults.standard.set(true, forKey: "firstTimer")
let mainPlayer = PlayerData()
let player1 = Player(entity: Player.entity(), insertInto: context)
player1.name = mainPlayer.name
performSegue(withIdentifier: "toMainViewController", sender: self)
saveItems()
}


func saveItems() {
do {
try context.save()
print("File Successfully saved!")
}catch {
print("Error saving Context (error)")
}
}



// MARK: Function to Save and Load data??
/*
// 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.
}
*/

func loadItems() {
let request = Player.fetchRequest() as NSFetchRequest<Player>
do {
player = try context.fetch(request)
print("Info loaded")
} catch {
print("Error fetching data from context (error)")
}
}
}


MainViewController being sent the information. I only want to send one item and save it to that main view controller.



import UIKit
import Foundation
import CoreData

class MainViewController: UIViewController {
//set up model object, buttons, and labels
// let player: Player!
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
private var appDelegate = UIApplication.shared.delegate as! AppDelegate
// lazy var nameText = Player(context: context)
// var playerInfo = [Player]()
lazy var player = [Player]()
let playerData = PlayerData()
var name = ""


@IBOutlet weak var playerName: UILabel!

@IBOutlet weak var currentLevel: UILabel!

@IBOutlet weak var xpCounter: UILabel!

@IBOutlet weak var playerProfileImage: UIImageView!



override func viewDidLoad() {
super.viewDidLoad()

// loadItems()
// name = playerData.name
if let nameOfPlayer = name.name {
print("This is what we see: (nameOfPlayer)")
playerName.text = nameOfPlayer
}
appDelegate.saveContext()

}

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// loadView()

}

@IBAction func menuButtonPressed(_ sender: Any) {

}

func loadItems() {
let request = Player.fetchRequest() as NSFetchRequest<Player>
do {
player = try context.fetch(request)
print("Info loaded")
} catch {
print("Error fetching data from context (error)")
}
}
// MARK : Add Name to Main View


// MARK : Add Xp To Main View

// MARK : Add UI Image to profile image view

// MARK: (Optional) Create a 'Choose a task button to segue to the task tab'


// MARK: Program the Progress Bar to update on xp gained and reset on level up


// MARK: Function to Save and Load data??
}


If dataSource code needed I will add upon request.



Thanks!










share|improve this question
















I have been working on this issue for two days now and sadly I cannot figure out the issue to my problem. I'm trying to take one item from my initial one time view controller and send that to my main view controller where it will be saved within the main view controller and will appear upon that controller when reloading the app.



Here is my app delegate code for the "first time" view controller



 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

if UserDefaults.standard.bool(forKey: "firstTimer") {
let storyBoard = UIStoryboard.init(name: "Main", bundle: nil)
let mainView = storyBoard.instantiateViewController(withIdentifier: "MainViewControllerID")
let nav = UINavigationController(rootViewController: mainView)
nav.navigationBar.isHidden = true
self.window?.rootViewController = nav
}
return true
}


containers and saveContext are default



import UIKit

import CoreData

class FirstTimeViewController: UIViewController {

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
private var appDelegate = UIApplication.shared.delegate as! AppDelegate
private var player = [Player]()





@IBOutlet weak var nameTextField: UITextField!

override func viewDidLoad() {
super.viewDidLoad()

// Do any additional setup after loading the view.
}

// This View Controller will only be used once upon the first time the app is being used.

// MARK: Make func that prepares for segue on initial opening of app


override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toMainViewController" {
let mainViewController = segue.destination as! UINavigationController
let destination = mainViewController.topViewController as! MainViewController
if let newPlayer = self.nameTextField.text{
destination.name.name = newPlayer
destination.playerData.name = newPlayer
saveItems()
}
}

}

@IBAction func continueButtonPressed(_ sender: UIStoryboardSegue) {
UserDefaults.standard.set(true, forKey: "firstTimer")
let mainPlayer = PlayerData()
let player1 = Player(entity: Player.entity(), insertInto: context)
player1.name = mainPlayer.name
performSegue(withIdentifier: "toMainViewController", sender: self)
saveItems()
}


func saveItems() {
do {
try context.save()
print("File Successfully saved!")
}catch {
print("Error saving Context (error)")
}
}



// MARK: Function to Save and Load data??
/*
// 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.
}
*/

func loadItems() {
let request = Player.fetchRequest() as NSFetchRequest<Player>
do {
player = try context.fetch(request)
print("Info loaded")
} catch {
print("Error fetching data from context (error)")
}
}
}


MainViewController being sent the information. I only want to send one item and save it to that main view controller.



import UIKit
import Foundation
import CoreData

class MainViewController: UIViewController {
//set up model object, buttons, and labels
// let player: Player!
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
private var appDelegate = UIApplication.shared.delegate as! AppDelegate
// lazy var nameText = Player(context: context)
// var playerInfo = [Player]()
lazy var player = [Player]()
let playerData = PlayerData()
var name = ""


@IBOutlet weak var playerName: UILabel!

@IBOutlet weak var currentLevel: UILabel!

@IBOutlet weak var xpCounter: UILabel!

@IBOutlet weak var playerProfileImage: UIImageView!



override func viewDidLoad() {
super.viewDidLoad()

// loadItems()
// name = playerData.name
if let nameOfPlayer = name.name {
print("This is what we see: (nameOfPlayer)")
playerName.text = nameOfPlayer
}
appDelegate.saveContext()

}

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// loadView()

}

@IBAction func menuButtonPressed(_ sender: Any) {

}

func loadItems() {
let request = Player.fetchRequest() as NSFetchRequest<Player>
do {
player = try context.fetch(request)
print("Info loaded")
} catch {
print("Error fetching data from context (error)")
}
}
// MARK : Add Name to Main View


// MARK : Add Xp To Main View

// MARK : Add UI Image to profile image view

// MARK: (Optional) Create a 'Choose a task button to segue to the task tab'


// MARK: Program the Progress Bar to update on xp gained and reset on level up


// MARK: Function to Save and Load data??
}


If dataSource code needed I will add upon request.



Thanks!







ios swift






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 14 '18 at 7:25









rmaddy

241k27316380




241k27316380










asked Nov 14 '18 at 6:23









Dreaming SavantDreaming Savant

266




266













  • What exactly do you need to pass from your One Time Initial VC to your Main View Controller?

    – Shubham Bakshi
    Nov 14 '18 at 6:31








  • 1





    Is there a reason why you need to send to the main view controller and then store it in core data? I mean could you not store it in core data in the initial view controller itself, and then just access the same value from core data in the main view controller and do what you need to do with it?

    – iOSer
    Nov 14 '18 at 6:38













  • @shubham I made the initial view controller very simple only sending a person's name to the main view controller.

    – Dreaming Savant
    Nov 14 '18 at 6:43











  • @iOSer I wanted to create a one time vc that would pass the person's name to the main view controller. I would like to do what you are suggesting. how would I go about accessing that value once saved?

    – Dreaming Savant
    Nov 14 '18 at 6:46






  • 1





    As @iOSer suggested, you don't need to pass data to another View Controller if the whole point of passing the data is to store it on the other end (like on your Main View Controller). You just save it within your Initial View Controller

    – Shubham Bakshi
    Nov 14 '18 at 6:46



















  • What exactly do you need to pass from your One Time Initial VC to your Main View Controller?

    – Shubham Bakshi
    Nov 14 '18 at 6:31








  • 1





    Is there a reason why you need to send to the main view controller and then store it in core data? I mean could you not store it in core data in the initial view controller itself, and then just access the same value from core data in the main view controller and do what you need to do with it?

    – iOSer
    Nov 14 '18 at 6:38













  • @shubham I made the initial view controller very simple only sending a person's name to the main view controller.

    – Dreaming Savant
    Nov 14 '18 at 6:43











  • @iOSer I wanted to create a one time vc that would pass the person's name to the main view controller. I would like to do what you are suggesting. how would I go about accessing that value once saved?

    – Dreaming Savant
    Nov 14 '18 at 6:46






  • 1





    As @iOSer suggested, you don't need to pass data to another View Controller if the whole point of passing the data is to store it on the other end (like on your Main View Controller). You just save it within your Initial View Controller

    – Shubham Bakshi
    Nov 14 '18 at 6:46

















What exactly do you need to pass from your One Time Initial VC to your Main View Controller?

– Shubham Bakshi
Nov 14 '18 at 6:31







What exactly do you need to pass from your One Time Initial VC to your Main View Controller?

– Shubham Bakshi
Nov 14 '18 at 6:31






1




1





Is there a reason why you need to send to the main view controller and then store it in core data? I mean could you not store it in core data in the initial view controller itself, and then just access the same value from core data in the main view controller and do what you need to do with it?

– iOSer
Nov 14 '18 at 6:38







Is there a reason why you need to send to the main view controller and then store it in core data? I mean could you not store it in core data in the initial view controller itself, and then just access the same value from core data in the main view controller and do what you need to do with it?

– iOSer
Nov 14 '18 at 6:38















@shubham I made the initial view controller very simple only sending a person's name to the main view controller.

– Dreaming Savant
Nov 14 '18 at 6:43





@shubham I made the initial view controller very simple only sending a person's name to the main view controller.

– Dreaming Savant
Nov 14 '18 at 6:43













@iOSer I wanted to create a one time vc that would pass the person's name to the main view controller. I would like to do what you are suggesting. how would I go about accessing that value once saved?

– Dreaming Savant
Nov 14 '18 at 6:46





@iOSer I wanted to create a one time vc that would pass the person's name to the main view controller. I would like to do what you are suggesting. how would I go about accessing that value once saved?

– Dreaming Savant
Nov 14 '18 at 6:46




1




1





As @iOSer suggested, you don't need to pass data to another View Controller if the whole point of passing the data is to store it on the other end (like on your Main View Controller). You just save it within your Initial View Controller

– Shubham Bakshi
Nov 14 '18 at 6:46





As @iOSer suggested, you don't need to pass data to another View Controller if the whole point of passing the data is to store it on the other end (like on your Main View Controller). You just save it within your Initial View Controller

– Shubham Bakshi
Nov 14 '18 at 6:46












2 Answers
2






active

oldest

votes


















1














Code is wrong. You should do more check



image






share|improve this answer


























  • Yes I recently changed the code in my latest attempt in passing and saving the data. I'll say that I didn't have trouble passing the data, but keeping that data on the main view was where my issue lied.

    – Dreaming Savant
    Nov 14 '18 at 6:42





















0














This is what I was able to achieve:



import UIKit
import CoreData
class FirstTimeViewController: UIViewController {

private var player = [Player]()
private var appDelegate = UIApplication.shared.delegate as! AppDelegate
private let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext




@IBOutlet weak var nameTextField: UITextField!

override func viewDidLoad() {
super.viewDidLoad()

// Do any additional setup after loading the view.
}

// This View Controller will only be used once upon the first time the app is being used.

// MARK: Make func that prepares for segue on initial opening of app


override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "toMainViewController" {
let entity = NSEntityDescription.entity(forEntityName: "Player", in: context)

let newPlayer = NSManagedObject(entity: entity!, insertInto: context)

if let newUser = self.nameTextField.text{
newPlayer.setValue(newUser, forKey: "name")
print("This is what i got: ", newPlayer)
}
appDelegate.saveContext()
}

}

@IBAction func continueButtonPressed(_ sender: UIStoryboardSegue) {
UserDefaults.standard.set(true, forKey: "firstTimer")

performSegue(withIdentifier: "toMainViewController", sender: self)
}


And for the Main View Controller:



import UIKit
import Foundation
import CoreData

class MainViewController: UIViewController {

//set up model object, buttons, and labels

let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
private var appDelegate = UIApplication.shared.delegate as! AppDelegate
lazy var player = [Player]()


@IBOutlet weak var playerName: UILabel!

@IBOutlet weak var currentLevel: UILabel!

@IBOutlet weak var xpCounter: UILabel!

@IBOutlet weak var playerProfileImage: UIImageView!



override func viewDidLoad() {
super.viewDidLoad()

let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Player")
// request.predicate = NSPredicate(format: "name = %@", "noon")
request.returnsObjectsAsFaults = false

do {
let result = try context.fetch(request)
for data in result as! [NSManagedObject] {
print(data.value(forKey: "name") as! String)
self.playerName.text = data.value(forKey: "name") as? String
}

} catch {
print("Failed")
}



}

override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// loadView()

}

@IBAction func menuButtonPressed(_ sender: Any) {

}





share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53294233%2fhow-to-pass-item-from-initial-one-time-first-time-view-controller-to-main-view%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    Code is wrong. You should do more check



    image






    share|improve this answer


























    • Yes I recently changed the code in my latest attempt in passing and saving the data. I'll say that I didn't have trouble passing the data, but keeping that data on the main view was where my issue lied.

      – Dreaming Savant
      Nov 14 '18 at 6:42


















    1














    Code is wrong. You should do more check



    image






    share|improve this answer


























    • Yes I recently changed the code in my latest attempt in passing and saving the data. I'll say that I didn't have trouble passing the data, but keeping that data on the main view was where my issue lied.

      – Dreaming Savant
      Nov 14 '18 at 6:42
















    1












    1








    1







    Code is wrong. You should do more check



    image






    share|improve this answer















    Code is wrong. You should do more check



    image







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Nov 14 '18 at 6:46

























    answered Nov 14 '18 at 6:40









    dengAprodengApro

    1,01411121




    1,01411121













    • Yes I recently changed the code in my latest attempt in passing and saving the data. I'll say that I didn't have trouble passing the data, but keeping that data on the main view was where my issue lied.

      – Dreaming Savant
      Nov 14 '18 at 6:42





















    • Yes I recently changed the code in my latest attempt in passing and saving the data. I'll say that I didn't have trouble passing the data, but keeping that data on the main view was where my issue lied.

      – Dreaming Savant
      Nov 14 '18 at 6:42



















    Yes I recently changed the code in my latest attempt in passing and saving the data. I'll say that I didn't have trouble passing the data, but keeping that data on the main view was where my issue lied.

    – Dreaming Savant
    Nov 14 '18 at 6:42







    Yes I recently changed the code in my latest attempt in passing and saving the data. I'll say that I didn't have trouble passing the data, but keeping that data on the main view was where my issue lied.

    – Dreaming Savant
    Nov 14 '18 at 6:42















    0














    This is what I was able to achieve:



    import UIKit
    import CoreData
    class FirstTimeViewController: UIViewController {

    private var player = [Player]()
    private var appDelegate = UIApplication.shared.delegate as! AppDelegate
    private let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext




    @IBOutlet weak var nameTextField: UITextField!

    override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    }

    // This View Controller will only be used once upon the first time the app is being used.

    // MARK: Make func that prepares for segue on initial opening of app


    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if segue.identifier == "toMainViewController" {
    let entity = NSEntityDescription.entity(forEntityName: "Player", in: context)

    let newPlayer = NSManagedObject(entity: entity!, insertInto: context)

    if let newUser = self.nameTextField.text{
    newPlayer.setValue(newUser, forKey: "name")
    print("This is what i got: ", newPlayer)
    }
    appDelegate.saveContext()
    }

    }

    @IBAction func continueButtonPressed(_ sender: UIStoryboardSegue) {
    UserDefaults.standard.set(true, forKey: "firstTimer")

    performSegue(withIdentifier: "toMainViewController", sender: self)
    }


    And for the Main View Controller:



    import UIKit
    import Foundation
    import CoreData

    class MainViewController: UIViewController {

    //set up model object, buttons, and labels

    let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    private var appDelegate = UIApplication.shared.delegate as! AppDelegate
    lazy var player = [Player]()


    @IBOutlet weak var playerName: UILabel!

    @IBOutlet weak var currentLevel: UILabel!

    @IBOutlet weak var xpCounter: UILabel!

    @IBOutlet weak var playerProfileImage: UIImageView!



    override func viewDidLoad() {
    super.viewDidLoad()

    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Player")
    // request.predicate = NSPredicate(format: "name = %@", "noon")
    request.returnsObjectsAsFaults = false

    do {
    let result = try context.fetch(request)
    for data in result as! [NSManagedObject] {
    print(data.value(forKey: "name") as! String)
    self.playerName.text = data.value(forKey: "name") as? String
    }

    } catch {
    print("Failed")
    }



    }

    override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    // loadView()

    }

    @IBAction func menuButtonPressed(_ sender: Any) {

    }





    share|improve this answer






























      0














      This is what I was able to achieve:



      import UIKit
      import CoreData
      class FirstTimeViewController: UIViewController {

      private var player = [Player]()
      private var appDelegate = UIApplication.shared.delegate as! AppDelegate
      private let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext




      @IBOutlet weak var nameTextField: UITextField!

      override func viewDidLoad() {
      super.viewDidLoad()

      // Do any additional setup after loading the view.
      }

      // This View Controller will only be used once upon the first time the app is being used.

      // MARK: Make func that prepares for segue on initial opening of app


      override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
      if segue.identifier == "toMainViewController" {
      let entity = NSEntityDescription.entity(forEntityName: "Player", in: context)

      let newPlayer = NSManagedObject(entity: entity!, insertInto: context)

      if let newUser = self.nameTextField.text{
      newPlayer.setValue(newUser, forKey: "name")
      print("This is what i got: ", newPlayer)
      }
      appDelegate.saveContext()
      }

      }

      @IBAction func continueButtonPressed(_ sender: UIStoryboardSegue) {
      UserDefaults.standard.set(true, forKey: "firstTimer")

      performSegue(withIdentifier: "toMainViewController", sender: self)
      }


      And for the Main View Controller:



      import UIKit
      import Foundation
      import CoreData

      class MainViewController: UIViewController {

      //set up model object, buttons, and labels

      let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
      private var appDelegate = UIApplication.shared.delegate as! AppDelegate
      lazy var player = [Player]()


      @IBOutlet weak var playerName: UILabel!

      @IBOutlet weak var currentLevel: UILabel!

      @IBOutlet weak var xpCounter: UILabel!

      @IBOutlet weak var playerProfileImage: UIImageView!



      override func viewDidLoad() {
      super.viewDidLoad()

      let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Player")
      // request.predicate = NSPredicate(format: "name = %@", "noon")
      request.returnsObjectsAsFaults = false

      do {
      let result = try context.fetch(request)
      for data in result as! [NSManagedObject] {
      print(data.value(forKey: "name") as! String)
      self.playerName.text = data.value(forKey: "name") as? String
      }

      } catch {
      print("Failed")
      }



      }

      override func viewWillAppear(_ animated: Bool) {
      super.viewWillAppear(animated)
      // loadView()

      }

      @IBAction func menuButtonPressed(_ sender: Any) {

      }





      share|improve this answer




























        0












        0








        0







        This is what I was able to achieve:



        import UIKit
        import CoreData
        class FirstTimeViewController: UIViewController {

        private var player = [Player]()
        private var appDelegate = UIApplication.shared.delegate as! AppDelegate
        private let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext




        @IBOutlet weak var nameTextField: UITextField!

        override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        }

        // This View Controller will only be used once upon the first time the app is being used.

        // MARK: Make func that prepares for segue on initial opening of app


        override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "toMainViewController" {
        let entity = NSEntityDescription.entity(forEntityName: "Player", in: context)

        let newPlayer = NSManagedObject(entity: entity!, insertInto: context)

        if let newUser = self.nameTextField.text{
        newPlayer.setValue(newUser, forKey: "name")
        print("This is what i got: ", newPlayer)
        }
        appDelegate.saveContext()
        }

        }

        @IBAction func continueButtonPressed(_ sender: UIStoryboardSegue) {
        UserDefaults.standard.set(true, forKey: "firstTimer")

        performSegue(withIdentifier: "toMainViewController", sender: self)
        }


        And for the Main View Controller:



        import UIKit
        import Foundation
        import CoreData

        class MainViewController: UIViewController {

        //set up model object, buttons, and labels

        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        private var appDelegate = UIApplication.shared.delegate as! AppDelegate
        lazy var player = [Player]()


        @IBOutlet weak var playerName: UILabel!

        @IBOutlet weak var currentLevel: UILabel!

        @IBOutlet weak var xpCounter: UILabel!

        @IBOutlet weak var playerProfileImage: UIImageView!



        override func viewDidLoad() {
        super.viewDidLoad()

        let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Player")
        // request.predicate = NSPredicate(format: "name = %@", "noon")
        request.returnsObjectsAsFaults = false

        do {
        let result = try context.fetch(request)
        for data in result as! [NSManagedObject] {
        print(data.value(forKey: "name") as! String)
        self.playerName.text = data.value(forKey: "name") as? String
        }

        } catch {
        print("Failed")
        }



        }

        override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // loadView()

        }

        @IBAction func menuButtonPressed(_ sender: Any) {

        }





        share|improve this answer















        This is what I was able to achieve:



        import UIKit
        import CoreData
        class FirstTimeViewController: UIViewController {

        private var player = [Player]()
        private var appDelegate = UIApplication.shared.delegate as! AppDelegate
        private let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext




        @IBOutlet weak var nameTextField: UITextField!

        override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        }

        // This View Controller will only be used once upon the first time the app is being used.

        // MARK: Make func that prepares for segue on initial opening of app


        override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "toMainViewController" {
        let entity = NSEntityDescription.entity(forEntityName: "Player", in: context)

        let newPlayer = NSManagedObject(entity: entity!, insertInto: context)

        if let newUser = self.nameTextField.text{
        newPlayer.setValue(newUser, forKey: "name")
        print("This is what i got: ", newPlayer)
        }
        appDelegate.saveContext()
        }

        }

        @IBAction func continueButtonPressed(_ sender: UIStoryboardSegue) {
        UserDefaults.standard.set(true, forKey: "firstTimer")

        performSegue(withIdentifier: "toMainViewController", sender: self)
        }


        And for the Main View Controller:



        import UIKit
        import Foundation
        import CoreData

        class MainViewController: UIViewController {

        //set up model object, buttons, and labels

        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        private var appDelegate = UIApplication.shared.delegate as! AppDelegate
        lazy var player = [Player]()


        @IBOutlet weak var playerName: UILabel!

        @IBOutlet weak var currentLevel: UILabel!

        @IBOutlet weak var xpCounter: UILabel!

        @IBOutlet weak var playerProfileImage: UIImageView!



        override func viewDidLoad() {
        super.viewDidLoad()

        let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Player")
        // request.predicate = NSPredicate(format: "name = %@", "noon")
        request.returnsObjectsAsFaults = false

        do {
        let result = try context.fetch(request)
        for data in result as! [NSManagedObject] {
        print(data.value(forKey: "name") as! String)
        self.playerName.text = data.value(forKey: "name") as? String
        }

        } catch {
        print("Failed")
        }



        }

        override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        // loadView()

        }

        @IBAction func menuButtonPressed(_ sender: Any) {

        }






        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Nov 15 '18 at 6:08









        iOSer

        816720




        816720










        answered Nov 14 '18 at 17:06









        Dreaming SavantDreaming Savant

        266




        266






























            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53294233%2fhow-to-pass-item-from-initial-one-time-first-time-view-controller-to-main-view%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Xamarin.iOS Cant Deploy on Iphone

            Glorious Revolution

            Dulmage-Mendelsohn matrix decomposition in Python