当我输入通知时,正在观看通知,并观看了相关教程:
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)
}
}
最佳答案
如果您希望开除日期为现在,那就是:
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)
}
关于ios - 如何在Swift3中执行timeIntervalSinceNow?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39605714/