OGeek|极客世界-中国程序员成长平台

标题: ios - 如何关闭通知内容扩展? [打印本页]

作者: 菜鸟教程小白    时间: 2022-12-11 19:17
标题: ios - 如何关闭通知内容扩展?

我想实现与 IOS 原始时钟应用程序相同的功能。但我遇到了一个障碍:当贪睡剩余时间设置为零时,我无法以编程方式关闭通知内容扩展。 图片如下: 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()
        }
    }
}



Best Answer-推荐答案


似乎从 iOS 12 开始有解决这个问题的方法:

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

关于ios - 如何关闭通知内容扩展?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42874245/






欢迎光临 OGeek|极客世界-中国程序员成长平台 (http://ogeek.cn/) Powered by Discuz! X3.4