如何在 Swift 3 中设置每天特定时间的闹钟?

Raz*_*riz 3 timer ios swift swift3

我正在使用 Swift 3 开发一个 iOS 应用程序,我需要运行一个代码来清除在特定时间(假设每天凌晨 1:00)使用的本地数据库。

我遇到过这个在给定时间运行代码的示例,但他给出的示例使用了代码运行时的时间间隔。这是发布的代码的修改版本:

func setAlarm(){
    print("set alarm called")
    let date = Date().addingTimeInterval(5 * 60 * 1)
    let timer = Timer(fireAt: date, interval: 0, target: self, selector: #selector(self.clearAllData), userInfo: nil, repeats: false)
    RunLoop.main.add(timer, forMode: RunLoopMode.commonModes)
}
Run Code Online (Sandbox Code Playgroud)

这段代码将在调用clearAllData函数代码5分钟后setAlarm()调用我的函数。这工作得很好,但这不是我想要的。我希望能够设置一个闹钟,该闹钟将在特定时间响起,而不是在 N 秒后响起。

我怎样才能做到这一点?

小智 5

我曾经做过一个这样的iOS应用程序,搜索了很多最后我使用了本地通知。延迟通知显示时间。试试这个并让我知道结果

`func scheduleNotification(date:String , time: String , subject:String) {

    var dateString = date+" "+time
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"

    let convertedDate = dateFormatter.date(from: dateString)!

    let subtractTime = Calendar.current.date(byAdding: .minute, value: -10, to: convertedDate)

    dateString = dateFormatter.string(from: subtractTime!)

    var localTimeZoneName: String { return TimeZone.current.identifier }
    var secondsFromGMT: Int { return TimeZone.current.secondsFromGMT() }
    dateFormatter.timeZone = TimeZone(secondsFromGMT: secondsFromGMT)
    dateFormatter.dateFormat = "dd-MM-yyyy HH:mm"

    let dateObj:Date = dateFormatter.date(from: dateString)!

    print("alaram time  : \(dateObj)")

    let triggerDaily = Calendar.current.dateComponents([.day,.month,.year,.hour,.minute,], from: dateObj)


    let trigger = UNCalendarNotificationTrigger(dateMatching: triggerDaily, repeats: true)

    let alarmId = UUID().uuidString

    let content = UNMutableNotificationContent()
    content.title = "your title"
    content.body = subject
    content.sound = UNNotificationSound.init(named: "your sound filename.mp3")
    content.categoryIdentifier = alarmId

    let request = UNNotificationRequest(identifier: alarmIdentifier, content: content, trigger: trigger)

    print("alarm identi   : \(alarmIdentifier)")

    UNUserNotificationCenter.current().delegate = self
    UNUserNotificationCenter.current().add(request) {(error) in

        if let error = error {
            print("Uh oh! i had an error: \(error)")
        }
    }
}`   
Run Code Online (Sandbox Code Playgroud)

以上func是设置通知

func playSound(_ soundName: String) {

    //vibrate phone first
    AudioServicesPlaySystemSound(SystemSoundID(kSystemSoundID_Vibrate))
    //set vibrate callback
    AudioServicesAddSystemSoundCompletion(SystemSoundID(kSystemSoundID_Vibrate),nil,
                                          nil,
                                          { (_:SystemSoundID, _:UnsafeMutableRawPointer?) -> Void in
                                            print("callback", terminator: "") //todo
    },
                                          nil)
    let url = URL(
        fileURLWithPath: Bundle.main.path(forResource: soundName, ofType: "mp3")!)

    var error: NSError?

    do {
        audioPlayer = try AVAudioPlayer(contentsOf: url)
    } catch let error1 as NSError {
        error = error1
        audioPlayer = nil
    }

    if let err = error {
        print("audioPlayer error \(err.localizedDescription)")
    } else {
        audioPlayer!.delegate = self
        audioPlayer!.prepareToPlay()
    }
    //negative number means loop infinity
    audioPlayer!.numberOfLoops = -1
    audioPlayer!.play()
}
Run Code Online (Sandbox Code Playgroud)

要播放声音,请传递您的 mp3 文件名,并将 audioPlayer 声明为AVAudioPlayer

playSound("Your sound file name")

    let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: UIAlertControllerStyle.actionSheet)
    actionSheet.view.tintColor = UIColor.black

    actionSheet.addAction(UIAlertAction(title: "Stop Alert", style: UIAlertActionStyle.default, handler: { (alert:UIAlertAction!) -> Void in


        self.audioPlayer?.stop()
    }))
    window?.rootViewController!.present(actionSheet, animated: true, completion: nil)
Run Code Online (Sandbox Code Playgroud)

在方法中添加这些代码UNUserNotificationCenterDelegate也想导入AudioToolBoxAVFoundation