Loading And Continuing To Add Integers Xcode Swift - ios

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()!
}

Related

Check if input countains numbers in 2 fields in xcode

So i recently tried to create a very simple calcylator in xcode, the problem i have is when i press the calculate button when there is no numbers there the app crashes, and when i put anything that isnt a number there and press the calculate button it also crash, and i know it crash cause it cant convert nothing/non numbers into a double, but how do i check if it is numbers in the textfields and if it is it will show the result off the
equation and if there is no number it will just set the textfeilds to nothing
(faktor1.text = "") (faktor2.text = "") ...
well it looks like this right now (ränka ut means calculate)
here is the code i used,
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var faktor1: UITextField!
#IBOutlet weak var faktor2: UITextField!
#IBOutlet weak var result: UILabel!
#IBOutlet weak var calculatebutton: UIButton!
#IBOutlet weak var clearui: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
result.text = ""
calculatebutton.layer.cornerRadius = 25.0
result.layer.cornerRadius = 25.0
clearui.layer.cornerRadius = 25.0
}
#IBAction func calculate( sender: Any) {
let input1 = Double(faktor1.text!)!
let input2 = Double(faktor2.text!)!
let calculation = input1 * input2
result.text = "(calculation)"
}
#IBAction func clearfnc( sender: Any) {
result.text = ""
faktor1.text = ""
faktor2.text = ""
}
}
You can simply unwrap your optionals the Swift way, instead of using ! (force unwrap)
This is an example using guard:
#IBAction func calculate(sender: Any) {
guard
let input1String = faktor1.text,
let input2String = faktor1.text,
let input1 = Double(input1String),
let input2 = Double(input2String)
else {
faktor1.text = ""
faktor1.text = ""
return
}
let calculation = input1 * input2
result.text = "\(calculation)"
}

Using UserDefaults to store score for a clicker game (Swift 5)

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.

leaderboard with persistent data in swift using usersdefault to save the values

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.

Data persistence after call to webservice iOS

Sorry for my English.
I have many problems in achieving data persistence after call the webservice .
Everything works correctly but I need to use that data in other methods .
As seen in the image once charge data on the screen then I want to give the user the option to use them well or load new data . But not as saving the data recovery webservice .
I was trying to use NSUserDefault but neither work .
From already thank you very much , any response is helpful .
Regards!
ViewController:
class ViewController: UIViewController {
let defaults = NSUserDefaults.standardUserDefaults()
#IBOutlet weak var myLabel2: UITextField!
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.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let newVC : SecondViewController = segue.destinationViewController as! SecondViewController
let telefono = myLabel2.text!
newVC.recibirString = telefono
}
#IBAction func mostrarAlgo(sender:AnyObject) {
//something
}
}
SecondViewController:
class SecondViewController: UIViewController {
let defaults = NSUserDefaults.standardUserDefaults()
var tel: String = ""
#IBOutlet weak var myLabel1: UITextField!
#IBOutlet weak var myLabel3: UITextField!
#IBOutlet weak var myLabel4: UITextField!
#IBOutlet weak var myLabel5: UITextField!
#IBOutlet weak var myLabel6: UITextField!
#IBOutlet weak var myLabel7: UITextField!
#IBOutlet weak var myLabel8: UITextField!
var recibirString = String()
override func viewDidLoad() {
super.viewDidLoad()
myLabel1.text = recibirString
performRequestAndUpdateUI2(myLabel1.text!)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func performRequestAndUpdateUI2(tel:String) {
WebService.llamarWebService (tel,completionHandler: { datos in
guard datos.count == 5 else {
self.myLabel8.text = ("El número ingresado no está registrado.")
return
}
guard datos[0] as! String == "OK" else {
print("not everything was OK")
return
}
dispatch_async(dispatch_get_main_queue()) {
self.myLabel3.text = datos[0] as? String
self.myLabel4.text = datos[1] as? String
self.myLabel5.text = datos[2] as? String
self.myLabel6.text = datos[3] as? String
self.myLabel7.text = datos[4] as? String
self.myLabel8.text = ("Usted está registrado.")
//need save this data
}
})
}
#IBAction func guardarDatos(sender: AnyObject) {
// do something
}
}
WebService:
class WebService{
var telefono = ""
class func llamarWebService(telefono:String, completionHandler: (datos:NSArray)->()){
let urlPath = "http://xxxxxxxxxxx.com.ar/xxxxxxxxxx/forwarder_number?phone=\(telefono)"
let url = NSURL(string: urlPath)
let session = NSURLSession.sharedSession()
var arreglo:NSArray!
let task = session.dataTaskWithURL(url!,completionHandler: {data,response,error -> Void in
if (error != nil){
print(error?.localizedDescription)
}
let nsdata: NSData = NSData(data: data!)
arreglo = self.retornarDatos(nsdata)
completionHandler(datos: arreglo)
})
task.resume()
}
class func retornarDatos(nsdata: NSData)-> Array<String>{
let datos = NSString(data:nsdata,encoding: NSUTF8StringEncoding)
let partes = datos?.componentsSeparatedByString(",")
var arreglo : [String] = []
for i in partes!{
arreglo.append(i)
}
return arreglo
}
}

Saving the selection of a Segmented control to NSuserdefaults

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")
}

Resources