I am using the segmented control as simple yes or no button. I would like to save the result of the selection after I change views by using NSuserdefaults the segmented control has two selections simply "yes" or "no" I have this currently
class DetailContactViewController: UIViewController {
#IBOutlet var attendingAnswer: UISegmentedControl!
#IBOutlet var name : UILabel!
#IBOutlet weak var contactImage: UIImageView!
#IBOutlet weak var email: UILabel!
#IBOutlet weak var attending : UILabel!
var contact : CNContact?
var defaults : NSUserDefaults = NSUserDefaults.standardUserDefaults()
override func viewDidLoad() {
super.viewDidLoad()
let formatter = CNContactFormatter()
if let contact = contact {
name.text = (contact.phoneNumbers.first?.value as! CNPhoneNumber).stringValue
email.text = (contact.emailAddresses.first?.value as? String)
defaults.setValue(true, forKey: name.text!)
defaults.valueForKey(name.text!)
}
// Do any additional setup after loading the view.
}
#IBAction func segmentedControlAction(sender: AnyObject) {
if(segementControl.selectedSegmentIndex == 0)
{
let segmentControl = NSUserDefaults.standardUserDefaults()
segmentControl.setBool(true, forKey: "KeyName")
}
else if(segementControl.selectedSegmentIndex == 1)
{
let segmentControl = NSUserDefaults.standardUserDefaults()
segmentControl.setBool(false, forKey: "KeyName")
}
//Fetch
let defaults = NSUserDefaults.standardUserDefaults()
let segementName = defaults.boolForKey("KeyName")
}
Related
Have made a simple incremental game. I want it so that even if I go to a different VC and then return to the game, or reopen the game, it will show the current score. My issue is that if I leave the game, then the score will return back to zero. I do not want that to happen. The score should not be resetting. I've heard I could use UserDefaults but I am not familiar to it at all. If you can explain using code, that would be best. Thanks.
import UIKit
class CookieClickerVC: UIViewController {
#IBOutlet weak var goldLabel: UILabel!
#IBOutlet weak var numberOfGold: UILabel!
#IBOutlet weak var getGoldButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
formatItems()
let defaults = UserDefaults.standard
defaults.set(0, forKey: "goldCount")
}
#IBAction func getGoldClicked(_ sender: Any) {
goldCount += 1
numberOfGold.text = ("\(goldCount)")
}`
also, you may have already figured out, but goldCount is an unresolved identifier. How should I change the code after button is clicked?
Step 1: declare your goldCount variable and set the initial value to 0
Step 2: on viewDidLoad, get the value stored in the UserDefaults and set it to goldCount
Step 3: Also update your label
Step 4: Update the value of goldCount in userDefaults
import UIKit
class CookieClickerVC: UIViewController {
#IBOutlet weak var goldLabel: UILabel!
#IBOutlet weak var numberOfGold: UILabel!
#IBOutlet weak var getGoldButton: UIButton!
//Step1: declare your goldCount variable and set initial value to 0
var goldCount = 0
override func viewDidLoad() {
super.viewDidLoad()
formatItems()
//Step2: on viewDidLoad, get the value stored in the UserDefaults and set it to goldCount
goldCount = UserDefaults.standard.integer(forKey: "goldCount")
//Step3: then also update your label
numberOfGold.text = ("\(goldCount)")
}
#IBAction func getGoldClicked(_ sender: Any) {
goldCount += 1
numberOfGold.text = ("\(goldCount)")
//Step4: update the value of goldCount in userDefaults
UserDefaults.standard.set(goldCount, forKey: "goldCount")
}
}
You can use these funtions to get and set score
class CookieClickerVC: UIViewController {
#IBOutlet weak var goldLabel: UILabel!
#IBOutlet weak var numberOfGold: UILabel!
#IBOutlet weak var getGoldButton: UIButton!
lazy var goldCount : Int = 0 {
didSet {
numberOfGold.text = ("\(goldCount)")
}
}
override func viewDidLoad() {
super.viewDidLoad()
formatItems()
goldCount = getScore()
}
#IBAction func getGoldClicked(_ sender: Any) {
goldCount += 1
savescore(goldCount)
}
// Save and Get methods ..
func saveScore(_ score:Int) {
let defaults = UserDefaults.standard
defaults.set(score, forKey: "goldCount")
// defaults.synchronize() its [unnecessary][1]
}
// defaults.synchronize() its unnecessary
func getScore()-> Int {
let defaults = UserDefaults.standard
return defaults.integer(forKey: "goldCount")
}
}
Try the below
class ViewController: UIViewController {
#IBOutlet weak var numberOfGold: UILabel!
#IBOutlet weak var highScore: UILabel!
//declare your count variable globally
var goldCount : Int = 0
let defaults = UserDefaults.standard
override func viewDidLoad() {
super.viewDidLoad()
//get the highscore and then set it to label
let userHighScore = getUserScore()
highScore.text = "\(userHighScore)"
}
#IBAction func goldButtonClicked(_ sender: Any) {
goldCount += 1
numberOfGold.text = "\(goldCount)"
}
//function to say game finished and store the score in userdefault
//call this function when the gameHasFinished
func gameFinished() {
saveUserScore(goldCount)
}
func saveUserScore(_ score:Int){
defaults.set(score, forKey: "goldCount")
}
func getUserScore()-> Int {
return defaults.integer(forKey: "goldCount")
}
}
You can change your viewDidLoad function to check the UserDefaults for the "goldCount" key first, and if it has a value, use it. If not just set the score to 0.
override func viewDidLoad() {
super.viewDidLoad()
formatItems()
let defaults = UserDefaults.standard
if let savedScore = defaults.value(forKey: "goldCount") as? Int {
goldCount = savedScore
} else {
defaults.set(0, forKey: "goldCount")
}
}
You can define "goldCount" as var goldCount: Int = 0 below your IBOutlets.
Also as a further optimization, you can extract the "goldCount" string to use as let goldCountKey: String = "goldCount" and use it like defaults.set(0, forKey: goldCountKey). Avoiding hard-coded strings is a good practice in my opinion, but not that crucial in this case.
To save the new value in every click, add UserDefaults.standard.set(goldCount, forKey: goldCountKey) in getGoldClicked. Another idea here would be to add this in your AppDelegate's willTerminate function to make sure you get your value saved when the application is terminated. Though that will require references to goldCount value there, so no rush.
Hope it helps!
import UIKit
class CookieClickerVC: UIViewController {
#IBOutlet weak var goldLabel: UILabel!
#IBOutlet weak var numberOfGold: UILabel!
#IBOutlet weak var getGoldButton: UIButton!
private var goldCount: Int = Int()
override func viewDidLoad() {
super.viewDidLoad()
formatItems()
}
#IBAction func getGoldClicked(_ sender: Any) {
goldCount += 1
numberOfGold.text = ("\(goldCount)")
UserDefaults.standard.set(goldCount, forKey: "goldCount")
UserDefaults.standard.synchronize()
//To get the count again you can use
print(UserDefaults.standard.integer(forKey: "goldCount")
}
Whenever there is an increment you can save the value of goldCount like this in your UserDefault and I have also added how can you fetch the same value from UserDefault.
I'm trying to create a leaderboard, but the player names and scores are not permanently saved, the "leaderboard" only contains the data from the most recent game in its text view. I tried making arrayOfData initially hold playerName and finalScore instead of being an empty array, but the problem still remains. How can I display playerName and playerScore in the leaderboard permanently and hove more names and scores added as more people play?
var finalScore = Int()
var playerName = String()
var allMyStoredData = UserDefaults.standard
var arrayOfData: [Any] = []
class secondVC: UIViewController {
#IBOutlet weak var scoreLabel: UILabel!
#IBOutlet weak var nameTF: UITextField!
#IBOutlet weak var doneButton: UIButton!
var playerScore = 0
var arrayOfData: [Any] = []
override func viewDidLoad() {
super.viewDidLoad()
scoreLabel.text = "Your score is: \(finalScore)"
loadData()
}
#IBAction func donePressed(_ sender: Any) {
saveData()
performSegue(withIdentifier: "toLeaderboard", sender: self)
}
func saveData () {
playerName = nameTF.text!
playerScore = finalScore
arrayOfData.append(playerName)
arrayOfData.append(playerScore)
allMyStoredData.set(playerName, forKey: "saveTheName")
allMyStoredData.set(playerScore, forKey: "saveTheScore")
allMyStoredData.set(arrayOfData, forKey: "saveTheArray")
}
func loadData () {
if let loadPlayerName:String = UserDefaults.standard.value(forKey: "saveTheName") as? String {
playerName = loadPlayerName
}
if let loadTheScore:Int = UserDefaults.standard.value(forKey: "saveTheName") as? Int {
playerScore = loadTheScore
}
}
}
//this is the code in the leaderboard's view controller
class leaderboardViewController: UIViewController {
#IBOutlet weak var theTextView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
theTextView.text = "\((arrayOfData).map{"\($0)"}.joined(separator: " Score: "))"
}
}
You are overwriting your saveTheArray item UserDefaults each time with a new array.
You want to fetch the saved array first, append the new game data, then re-save as so:
//Create user defaults instance
let userDefaults = UserDefaults.standard
//User defaults key
let historicalGameDataKey = "historicalGameData"
//Fetch game data array
var historicalGameData = userDefaults.array(forKey: historicalGameDataKey)
//Create array if it is nil (i.e. very first game)
if historicalGameData == nil {
historicalGameData = []
}
//Create game data dictionary
let gameData = [
"playerName": playerName,
"playerScore": playerScore
]
//Append game data dictionary to the array
historicalGameData?.append(["playerName": gameData])
//Save the updated array
userDefaults.set(historicalGameData, forKey: historicalGameDataKey
Core Data would be a better way to store this data, but this example should solve your problem using UserDefaults.
How can i passing data uiviewController from uiview
I am Using function but it was not working
protocol name is startcalldelegate and function name is startcall
UIView Code
protocol StartCallDelegate: class {
func startCall(localNickname :String, remoteNickname :String)}
class CardView: UIView {
let managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
weak var delegate: CardViewDelegate?
weak var socketdelegate: StartCallDelegate?
#IBOutlet weak var UserPhoto: UIImageView!
#IBOutlet weak var UserNickName: UILabel!
#IBOutlet weak var UserAge: UILabel!
#IBOutlet weak var UserPeople: UILabel!
var localNickname: String = ""
var remoteNickname: String = ""
#IBAction func SendMessage(_ sender: Any) {
print("SendMessage")
//print(localNickName)
//print(UserNickName.text!)
}
#IBAction func SendVideoCall(_ sender: Any) {
print("SendVideoCall")
let entityDescription = NSEntityDescription.entity(forEntityName: "Profile", in: managedObjectContext)
let request = NSFetchRequest<NSFetchRequestResult>()
request.entity = entityDescription
do {
let objects = try managedObjectContext.fetch(request)
if objects.count > 0 {
let match = objects[0] as! NSManagedObject
localNickname = match.value(forKey: "nick") as! String
} else {
print("Nothing founded")
}
} catch {
print("error")
}
remoteNickname = UserNickName.text!
socketdelegate?.startCall(localNickname: localNickname, remoteNickname: remoteNickname)
delegate?.VideoChatSegue()
}
}
UIViewcontroller Code
class ViewController: UIViewcontroller, StartCallDelegate {
var localNickname: String = ""
var remoteNickname: String = ""
override func viewDidLoad() {
super.viewDidLoad()
print(localNickname)
print(remoteNickname)
}
func startCall(localNickname: String, remoteNickname: String) {
print("Action startcall func")
self.localNickname = localNickname
self.remoteNickname = remoteNickname
}
startCall func not working
You need to define delegate in viewcontroller' ViewDidLoad
let objOardView = CardView() // this is only test purpose
objOardView.socketdelegate = self
I'm working on a project that is written in swift 3.0. My requirement is to retrieve and populate the data on a table view which is saved on CoreData that I enter on some text fields, thus once a row is selected I wants to update that record (re-assign values on my text fields and save).
Basically I have an entity named "UserIncome" and it got few attributes. Thus, when I wants to edit the data that I entered, I tap on a row and it'll direct me to the ViewController where I initially entered those data. However when I click the add button and save the data im getting duplicated data and they get populate in my table view. how can I stop this. The code of the class where i save data as follow.
import UIKit
import CoreData
class AddIncomeViewController:UIViewController,UITableViewDelegate,UITableViewDataSource {
#IBOutlet weak var toDateView: UIView!
#IBOutlet weak var setDateFromView: UIView!
#IBOutlet weak var datePickerTo: UIDatePicker!
#IBOutlet weak var datePickerFrom: UIDatePicker!
#IBOutlet weak var dropDowntableView: UITableView!
#IBOutlet weak var fromTextField: UITextField!
#IBOutlet weak var toTextField: UITextField!
#IBOutlet weak var amountTextField: UITextField!
#IBOutlet weak var incomeTypeLabel: UILabel!
#IBOutlet weak var incomeNameTextField: UITextField!
var myArray = ["Recurring Income", "Other Income"]
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
var store : UserIncome?
var otherInc : UserIncome?
override func viewDidLoad() {
super.viewDidLoad()
if let s = store {
incomeNameTextField.text = s.incomeName
amountTextField.text = s.amount
fromTextField.text = s.fromDate
toTextField.text = s.toDate
incomeTypeLabel.text = s.incomeType
}
if let o = otherInc {
incomeNameTextField.text = o.incomeName
amountTextField.text = o.amount
fromTextField.text = o.fromDate
toTextField.text = o.toDate
incomeTypeLabel.text = o.incomeType
}
}
#IBAction func cancelButtonPressed(_ sender: AnyObject) {
navigationController!.popViewController(animated: true)
}
#IBAction func addButtonPressed(_ sender: AnyObject) {
if store == nil{
let storeDesciption = NSEntityDescription.entity(forEntityName: "UserIncome", in: context)
store = UserIncome(entity:storeDesciption! , insertInto: context)
//otherInc = UserIncome(entity:storeDesciption! , insertInto: context)
}
if otherInc == nil{
let storeDesciption = NSEntityDescription.entity(forEntityName: "UserIncome", in: context)
otherInc = UserIncome(entity:storeDesciption! , insertInto: context)
}
store?.incomeName = incomeNameTextField.text
store?.amount = amountTextField.text
store?.fromDate = fromTextField.text
store?.toDate = toTextField.text
store?.incomeType = incomeTypeLabel.text
otherInc?.incomeName = incomeNameTextField.text
otherInc?.amount = amountTextField.text
otherInc?.fromDate = fromTextField.text
otherInc?.toDate = toTextField.text
otherInc?.incomeType = incomeTypeLabel.text
var error : NSError?
(UIApplication.shared.delegate as! AppDelegate).saveContext()
if let err = error{
let a = UIAlertView(title: "Success", message: err.localizedFailureReason, delegate: nil, cancelButtonTitle: "OK")
a.show()
}else {
let a = UIAlertView(title: "Success", message: "Successfully saved", delegate: nil, cancelButtonTitle: "OK")
a.show()
// navigationController!.popViewController(animated: true)
}
You added two different UserIncome objects. You should add one, and share it for your table views.
I am able to save an integer and load it using NSUserdeafaults but when I load up the number and try to continue adding to that number it starts at 0.
Example: I press the button 7 times and switch to a different page. I go back and click load button and it days 7. When I click it again it says 1.
Here is my "press for money" code:
//Press for Money
#IBAction func MoneyPress(sender: AnyObject) {
Money += 1
var MoneyNumberString:String = String(format: "Dollars:%i", Money)
self.DollarsLabel.text = (string: MoneyNumberString)
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(MoneyNumberString, forKey: "money")
defaults.synchronize()
}
Loading Code:
#IBAction func LoadTestButton(sender: UIButton) {
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
var money = defaults.valueForKey("money") as? String
DollarsLabel.text! = money!
}
Please help if you know how to make it continue adding to that number.
Full Code:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var MoneyButton: UIButton!
#IBOutlet weak var OptionButton: UIButton!
#IBOutlet weak var FeelingLuckyButton: UIButton!
#IBOutlet weak var TrophiesButton: UIButton!
#IBOutlet weak var DollarsLabel: UILabel!
#IBOutlet weak var BuyNowOne: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
var Money = Int(0)
//Press for Money
#IBAction func MoneyPress(sender: AnyObject) {
Money += 1
var MoneyNumberString:String = String(format: "Dollars:%i", Money)
self.DollarsLabel.text = (string: MoneyNumberString)
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(MoneyNumberString, forKey: "money")
defaults.synchronize()
}
#IBAction func LoadTestButton(sender: UIButton) {
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
var money = defaults.valueForKey("money") as? String
DollarsLabel.text! = money!
}
}
The problem is that you're setting Money to 0 when you actually want to set it to contain the value in your NSUserDefaults. To do that in your LoadTestButton method, try this:
#IBAction func LoadTestButton(sender: UIButton) {
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
var money = defaults.valueForKey("money") as? String
DollarsLabel.text! = money!
// Set "Money" to contain the numbers in your "money"
// string converted to an Int
Money = money!.stringByTrimmingCharactersInSet(NSCharacterSet.decimalDigitCharacterSet().invertedSet).toInt()!
}