比较函数运行后的变量 - Swift

时间:2016-03-01 18:39:04

标签: ios swift swift2

我是Xcode和swift的新手,正在创建一个闹钟应用程序。我无法弄清楚如何开始检查用户为闹钟设置的时间(闹钟时间)是否等于当前时间。

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

    }


}

我认为这可以通过在用户设置警报时在setAlarm函数内运行一些代码或在viewDidLoad()中完成。注释掉的线是我的尝试,但它不起作用。

我如何检查当前时间和设定时间是否相同?

1 个答案:

答案 0 :(得分:1)

使用NSDate对象进行数学计算,例如设置闹钟时间

let now = NSDate()
self.alarmTime = NSCalendar.currentCalendar().dateBySettingHour(17, minute: 38, second: 00, ofDate: now, options: NSCalendarOptions())

并在currentTime()方法

中连续比较日期
let date = NSDate()
if alarmTime?.compare(date) != .OrderedDescending  {
  print("Alarm")
}

!= .OrderedDescending表示:date等于或晚于alarmTime