如何关闭通知内容扩展?

时间:2017-03-18 12:10:35

标签: ios notifications

我希望实现与IOS原始时钟app相同的功能。但是我遇到了一个障碍:当暂停剩余时间设置为零时,我无法以编程方式关闭通知内容扩展。 图片如下: enter image description here

我的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()
        }
    }
}

1 个答案:

答案 0 :(得分:0)

在iOS 12中似乎可以解决此问题:

   if #available(iOSApplicationExtension 12.0, *) {
                    //self.extensionContext?.performNotificationDefaultAction()
                    self.extensionContext?.dismissNotificationContentExtension()
    }
相关问题