Liudvikas Launikonis Liudvikas Launikonis - 2 months ago 21
iOS Question

Having problems with saving and loading in Swift 3.0 iOS 10

I'm really new to the Swift and iOS programming scene and I am trying to learn a bunch of things. For this app, I want to save and load just one integer, but I am having problems, as everything I found on stack overflow and the Internet just doesn't seem to work on Swift 3. The app crashes immediately, it breaks on:

@IBOutlet weak var StaticLabel: UILabel!


It says "Thread 1: breakpoint 3.5" . Any help and tips would be very much appreciated :)

import UIKit
import AVFoundation

var player: AVAudioPlayer?
var number = 0

class ViewController: UIViewController {
@IBOutlet weak var StaticLabel: UILabel!
@IBOutlet weak var NumberLabel: UILabel!
let defaults = UserDefaults.standard

override func viewDidLoad() {
super.viewDidLoad()
Load()
}

func Load()
{
number = defaults.integer(forKey: "Save")
NumberLabel.text = String(number)
}

func playSound()
{
let path = Bundle.main.path(forResource: "RightYouAre.mp3", ofType: nil)
let url = URL(fileURLWithPath: path!)

do {
let sound = try AVAudioPlayer(contentsOf: url)
player = sound
sound.play()
}
catch {
// couldn't load file :(
}

}


@IBAction func Minus(_ sender: AnyObject) {
number = number - 1
NumberLabel.text = String(number)
defaults.set(number, forKey: "Save")
}

@IBAction func Plus(_ sender: UIButton) {
playSound()
number = number + 1
NumberLabel.text = String(number)
defaults.set(number, forKey: "Save")
}
}

Answer

your line of code

number = defaults.integer(forKey: "Save")

user defaults integer for key Save is nil, actually this key does not exist at all in the user defaults

before you load this integer from user defaults , it has to be set first

 if defaults.object(forKey: "Save") !=    nil { number =    defaults.integer(forKey: "Save") }

this will make sure the object exists in the user defaults before getting it's value

finally your load function should be

 func Load() {
     if defaults.object(forKey: "Save") != nil { 
number = defaults.integer(forKey: "Save") 
}
   NumberLabel.text = String(number)

}