首页 > 解决方案 > 迅速。通过按下按钮获得通知访问权限

问题描述

我确定 func 中的代码是正确的,因为它适用于启动应用程序,但不适用于我需要的按钮。

我试图将通知放在按钮内,但它不起作用

class SecondViewController: UIViewController {
    /*
    override func viewDidLoad() {
        super.viewDidLoad()
    }*/

    @IBAction func SubscribeButtonTapped(_ sender: Any) {

        // Step 1: Ask for permission
               let center = UNUserNotificationCenter.current()
               center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in

               }
               // Step 2: Create the notification content
               let content = UNMutableNotificationContent()
               content.title = "Take your ass off"
               content.body = "Do something!"
               content.sound = UNNotificationSound.default


               //Step 3: Create the notification trigger
               let date = Date().addingTimeInterval(10)
               let dateComponents = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: date)
               let trigger = UNCalendarNotificationTrigger.init(dateMatching: dateComponents, repeats: false)

               //Step 4: Create the request
               let uuidString = UUID().uuidString
               let request = UNNotificationRequest.init(identifier: uuidString, content: content, trigger: trigger)

               //Step 5: Register the request
               center.add(request) { (error) in
                   //Check the error paramater and handle any errors
        }        
    }

标签: swiftnotifications

解决方案


如果你写let date = Calendar.current.date(byAdding: .second, value: 1, to: Date())!它会在一秒钟后添加通知。但是,不要尝试在一秒钟内添加超过一个。您至少需要设置一分钟。否则你的应用会崩溃。


推荐阅读