[英]How to do timeIntervalSinceNow in Swift3?
我正在发布通知并观看教程,当我输入时:
notification.fireDate = NSDate(timeIntervalSinceNow: 0)
它说
参数标签'(timeIntervalSinceNow :)'与任何可用的重载都不匹配
我该如何解决? 这是我的代码:
import UIKit
import UserNotifications
class ViewController: UIViewController {
var timer = Timer()
var time = 10
override func viewDidLoad() {
super.viewDidLoad()
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: Selector(("Notification")), userInfo: nil, repeats: true)
// Do any additional setup after loading the view, typically from a nib.
}
func notification() {
time -= 1
if time <= 0 {
let notification = UILocalNotification()
notification.alertAction = "Call"
notification.alertBody = "You have a call right now"
notification.fireDate = NSDate(timeIntervalSinceNow: 0)
UIApplication.shared.scheduleLocalNotification(notification)
timer.invalidate()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func pushNotification(_ sender: AnyObject) {
let AlertView = UIAlertController(title: "Time for your call!", message: "Press go to continue", preferredStyle: .alert)
AlertView.addAction(UIAlertAction(title: "Go", style: .default, handler: nil))
self.present(AlertView, animated: true, completion: nil)
}
}
斯威夫特3
let minute:TimeInterval = 11.0 * 60.0;
Date(timeIntervalSinceNow: minute);
到现在为+11分钟。
如果您想要现在的开火日期,它只是:
notification.fireDate = Date()
正如Leo在别处指出的那样,选择器是不正确的。 它应该是:
weak var timer: Timer?
var time = 10
override func viewDidLoad() {
super.viewDidLoad()
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(handleTimer(_:)), userInfo: nil, repeats: true)
}
func handleTimer(_ timer: Timer) {
time -= 1
if time <= 0 {
let notification = UILocalNotification()
notification.alertAction = "Call"
notification.alertBody = "You have a call right now"
notification.fireDate = Date()
UIApplication.shared.scheduleLocalNotification(notification)
timer.invalidate()
}
}
然后你问:
这肯定有效,但现在我离开应用程序时没有得到通知
当您离开应用程序时,您不会收到通知,因为当应用程序未运行时, Timer
不会继续触发。 最好完全取消计时器,并立即安排本地通知所需的时间。 例如,要在10秒内安排本地通知:
override func viewDidLoad() {
super.viewDidLoad()
scheduleLocalNotification(delay: 10)
}
func scheduleLocalNotification(delay: TimeInterval) {
let notification = UILocalNotification()
notification.alertAction = "Call"
notification.alertBody = "You have a call right now"
notification.fireDate = Date().addingTimeInterval(delay)
UIApplication.shared.scheduleLocalNotification(notification)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.