I want to achieve the same function as the IOS original clock app.But I meet one barrier: I can't close the notification content extension programmatically when the snooze remaining time has been set zero. The picture is below:
my NotificationViewController.swift:
import UIKit
import UserNotifications
import UserNotificationsUI
class NotificationViewController: UIViewController, UNNotificationContentExtension {
@IBOutlet var label: UILabel?
var previousNotification: UNNotification?
var secondsDown = Int()
var countDownTimer: Timer?
override func viewDidLoad() {
super.viewDidLoad()
let size = view.bounds.size
preferredContentSize = CGSize(width: size.width, height: size.width * 0.7)
}
func didReceive(_ notification: UNNotification) {
previousNotification = notification
// Calculate the actual remaining seconds.
let timeInterval = -(notification.date.timeIntervalSinceNow)
secondsDown = (notification.request.content.userInfo["snoozeTime"] as! Int) * 60 - Int(timeInterval) - 1
// Achieve count down timer.
if countDownTimer == nil {
countDownTimer = Timer(timeInterval: 1, target: self, selector: #selector(self.countDownAction), userInfo: nil, repeats: true)
RunLoop.main.add(countDownTimer!, forMode: .defaultRunLoopMode)
}
// print the remaining time to text label.
let miniute = String(format:"%ld", (secondsDown / 60))
let second = String(format:"%02ld", (secondsDown % 60))
let formatTime = String(format: "%@:%@", miniute, second)
self.label?.text = String(format: "%@", formatTime)
}
func countDownAction(timer: Timer) {
secondsDown -= 1
let miniute = String(format:"%ld", (secondsDown / 60))
let second = String(format:"%02ld", (secondsDown % 60))
let formatTime = String(format: "%@:%@", miniute, second)
self.label?.text = String(format: "%@", formatTime)
if secondsDown == 0 {
countDownTimer?.invalidate()
}
}
}
It seems that from iOS 12 there is a solution to this problem:
if #available(iOSApplicationExtension 12.0, *) {
//self.extensionContext?.performNotificationDefaultAction()
self.extensionContext?.dismissNotificationContentExtension()
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.