Reputation: 283
I'm new to Xcode and swift and am creating an alarm clock app. I can't figure out how to start checking if the time set by the user for the alarm to go off (alarmTime) is equal to the current time.
import UIKit
import AVFoundation
class ViewController: UIViewController {
var alarmBeep = AVAudioPlayer()
var alarmTime = String?()
@IBOutlet weak var AlarmSetLabel: UILabel!
@IBOutlet weak var TimeLabel: UILabel!
@IBAction func SetAlarm(sender: UIButton) {
setAlarmTime()
}
@IBOutlet weak var AlarmButton: UIButton!
@IBAction func AlarmButton(sender: UIButton) {
alarmOff()
}
func twoDigits(number : Int) -> String {
var outNum = String(number)
if outNum.characters.count == 1 {
outNum = "0" + outNum
}
return outNum
}
func setAlarmTime() {
self.alarmTime = "17:38"
AlarmSetLabel.text = "Alarm Set for " + self.alarmTime!
//Start checking at this point
}
func compareTimes(time: String) {
if self.alarmTime == time {
alarmBeep.play()
AlarmButton.setTitle("Turn Off Alarm", forState: .Normal)
}
}
func alarmOff() {
alarmBeep.stop()
self.alarmTime = nil
}
func currentTime() -> String {
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([ .Hour, .Minute, .Second], fromDate: date)
let hour = twoDigits(components.hour)
let minutes = twoDigits(components.minute)
TimeLabel.text = hour + ":" + minutes
return hour + ":" + minutes
}
override func viewDidLoad() {
super.viewDidLoad()
currentTime()
_ = NSTimer.scheduledTimerWithTimeInterval(5, target:self, selector: Selector("currentTime"), userInfo: nil, repeats: true)
//_ = NSTimer.scheduledTimerWithTimeInterval(5, target:currentTime(), selector: Selector("compareTimes"), userInfo: nil, repeats: true)
let filePath = NSBundle.mainBundle().pathForResource("Bleep-sound", ofType: "mp3")
if let filePath = filePath {
let filePathURL = NSURL(fileURLWithPath: filePath)
do {
try alarmBeep = AVAudioPlayer(contentsOfURL: filePathURL)
alarmBeep.numberOfLoops = -1
//alarmBeep.play()
}
catch {
print("error")
}
}
}
}
I think this would be done by running some code either inside the setAlarm function when the user sets the alarm or in viewDidLoad(). The commented out line was my attempt but it doesn't work.
How would I check if the current and set times are the same?
Upvotes: 0
Views: 71
Reputation: 285290
Do the math with NSDate
objects for example set the alarm time
let now = NSDate()
self.alarmTime = NSCalendar.currentCalendar().dateBySettingHour(17, minute: 38, second: 00, ofDate: now, options: NSCalendarOptions())
and compare the dates continuously in the currentTime()
method
let date = NSDate()
if alarmTime?.compare(date) != .OrderedDescending {
print("Alarm")
}
!= .OrderedDescending
means: is date
equal or later than alarmTime
Upvotes: 1