Swift 3 - 每天在特定时间设置闹钟?

Swift 3 - 每天在特定时间设置闹钟?

问题描述:

我正在开发一个使用Swift 3的iOS应用程序,并且我需要运行一段代码来清除在特定时间使用的本地数据库(比如说每天上午1:00)。Swift 3 - 每天在特定时间设置闹钟?

我碰到了this example for running a code at a given time,但他给出的例子使用了代码运行时的时间间隔。下面的代码的修改版本发布:

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

此代码将调用我clearAllData函数的函数setAlarm()代码后的5分钟之称。这工作得很好,但它不是我想要的。我希望能够设置一个在某个特定时间将会关闭的闹钟,而不是在几秒钟后。

任何人都可以告诉我如何设置在特定时间将会关闭的闹钟吗?

任何帮助将非常感激。谢谢。

据我所知,由于iOS中的背景模式限制,无法完成此操作。请参阅Background modes。只要你的应用不属于这些,你就不能要求你的代码在当天(或者晚上)的特定时间开火。

我假设你的应用程序不会出现在前台(基于凌晨1时)

作为变通,你可以在所述时间推出了本地通知,要求用户清除(尽管看起来很愚蠢)

或者如果你的应用确实支持上述模式,你可以选择this答案。

我已经做了这样的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)") 
     } 
    } 
}` 

上述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() 
} 

播放的声音传递你的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) 

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