Home > Software engineering >  Every time i try to run my app and press a button the app crashes and gives me this Error, "Une
Every time i try to run my app and press a button the app crashes and gives me this Error, "Une

Time:01-02

This is the code and it's giving me an Error from let coffee = sender.currentTitle! that's my problem.

I'm trying to make my button be the name of the button which is Decaf but when i press it it gives me that Error.

import UIKit
import AVFoundation

class ViewController: UIViewController {
    
    override func viewDidLoad() {
       super.viewDidLoad()
        // Do any additional setup after loading the view.
    
}


    
    @IBOutlet weak var progressBar: UIProgressView!
       
    @IBOutlet weak var titleLabel: UILabel!
    
    let coffeeTimes = ["Decaf": 5, "coffee": 5]
    var timer = Timer()
    var player: AVAudioPlayer!
    var totalTime = 0
    var secondsPassed = 0
    
    @IBAction func coffeeSelected(_ sender: UIButton) {
       
        timer.invalidate()
        let coffee = sender.currentTitle! //1.This is the line were its giving me the Error"
        totalTime = coffeeTimes[coffee]!
        
        progressBar.progress = 0.0
        secondsPassed = 0
        titleLabel.text = coffee



        timer = Timer.scheduledTimer(timeInterval: 1.0, target:self, selector: #selector(updateTimer), userInfo:nil, repeats: true)
    }
    
    @objc func updateTimer() {
        if secondsPassed < totalTime {
            secondsPassed  = 1
            progressBar.progress = Float(secondsPassed) / Float(totalTime)
            print(Float(secondsPassed) / Float(totalTime))
        } else {
            timer.invalidate()
            titleLabel.text = "check coffee"
            
            let url = Bundle.main.url(forResource: "alarm_sound", withExtension: "mp3")
            player = try! AVAudioPlayer(contentsOf: url!)
            player.play()
        }
    }
}

CodePudding user response:

Use optional binding so the app doesn't crash. This if let statement will only run if "currentTitle" actually exists, in your case, it doesn't, so there must be some other problem in your code.

if let coffee = sender.currentTitle {
    totalTime = coffeeTimes[coffee]
    titleLabel.text = coffee
    progressBar.progress = 0.0
    secondsPassed = 0
}

An alternative is to return from the whole function if the value doesn't exist. Don't use both at the same time.

guard let coffee = sender.currentTitle else { return }

  • Related