Liangn1an
Liangn1an

Reputation: 43

SwiftUI compare time code crashed on iPhone 8 mini and iPhone 12 mini IOS 16

Please help it has drove me mad I am using Xcode 14, both crashed device using IOS 16. I have following code, it does not work on iPhone 8 Mini, iPhone 12 mini Real Device. it does work on the iPhone 12 Mini and iPhone 8 mini simulator and other real bigger sized iPhone Device. I downloaded time string such as "19:00" if the current time less than this, button activated else disable button.

        let date = Date()
        let calender = Calendar.current
        
        let hour = calender.component(.hour, from: date)
        let minute = calender.component(.minute, from: date)
        
        let slotTime = splitTime(string: time.Time)
        
        
        let CurrentTimeString = "\(hour):\(minute)"
        let TimeSlotTimeString = slotTime
        let f = DateFormatter()
        f.dateFormat = "HH:mm"
        
        if f.date(from: CurrentTimeString)! > f.date(from: slotTime)! {
            return true
        } else {
            return false
        }
    }

the crash message read found nil while unwrapping enter image description here

/// I use my mouse over the error area, the Xcode does show the value.

enter image description here ///

enter image description here

Upvotes: 0

Views: 91

Answers (1)

Duncan C
Duncan C

Reputation: 131481

Please edit your question to include your code As code not as screen-shots. If you also want to leave the screen-shots so we can see the crash info, fine, but we need the code.

Your code is using force-unwrapping.

I call the force-unwrap operator the "crash if nil" operator. That is what it does.

Don't use force-unwrapping. Rewrite your code to log a message if the date string can't be converted to a Date

You might have your different devices set up to different locales where the rules for date/time formatting are different.

Try displaying the current Date()to a string using your date formatter on each device and logging it to the console. My guess is that some of your devices are set to 12-hour time and some are set to 24 hour time.

When in 12 hour time the Date string "18:20" won't be valid.

Upvotes: 0

Related Questions