ios - 如何关闭通知内容扩展?

标签 ios notifications

我想实现与 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()
        }
    }
}

最佳答案

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

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

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

相关文章:

ios - 在 iOS 15 之前,我只能发送声音本地通知,现在我必须显示横幅

azure - 服务总线通知中心 : What is the payload size limit for the push notification?

iOS UIWebView 加载完成后不会更新其大小

android - 向特定用户发送推送通知 - Cordova

ios - 无法修改 UIBarButton tintColor

ios - 在 Swift 中每天刷新一次应用程序的 JSON 内容

ios - Youtube 解雇事件(iOS)

ruby - 扩展 ActiveSupport::Notifications.subscribe, instantiation.active_record 钩子(Hook)

ios - 如何使用Codable解码字典的JSON字典(具有不同的键)?

iphone - 将 xcode 4.6 iPhone 应用程序转换为通用应用程序