@Bear027

Как вызвать функцию Swift?

Мне сказали, что мои локальные уведомления не работаю потому что нет вызова ф-ии prepareAndSendLocalNotifications. Как её правильно вызвать и в каком месте? В swift новичок. Не судите строго.

import UIKit
import UserNotifications


    func prepareAndSendLocalNotifications() {
        // Prepare your notifications
        
        let oneHourNotifContent = UNMutableNotificationContent()
        oneHourNotifContent.title = "One hour"
        oneHourNotifContent.body = "It's been one hour since you logged in"
        oneHourNotifContent.sound = UNNotificationSound.default()
        oneHourNotifContent.userInfo = ["timeInterval": 10, "identifier": "Bear"]
        // The key is to use the userInfo of the notification content to pass anything you need
        
        let twoHourNotifContent = UNMutableNotificationContent()
        twoHourNotifContent.title = "Two hours"
        twoHourNotifContent.body = "It's been two hours since you logged in"
        twoHourNotifContent.sound = UNNotificationSound.default()
        twoHourNotifContent.userInfo = ["timeInterval": 20, "identifier": "Wolf"]
        
        // Create a list of them
        let localNotifList: [UNMutableNotificationContent] = [oneHourNotifContent, twoHourNotifContent]
        
        // Iterate to send all of them
        localNotifList.forEach { (notification) in
            scheduleNotification(notification: notification)
        }
    }


    func scheduleNotification(notification: UNMutableNotificationContent) {
        
        // Get the value for "timeInterval" key.
        guard let timeInterval = notification.userInfo["timeInterval"] as? Double else { return }
        guard let identifier = notification.userInfo["identifier"] as? String else { return }
        
        let date = Date(timeIntervalSinceNow: timeInterval)
        
        let calendar = Calendar(identifier: .gregorian)
        let components = calendar.dateComponents([.month, .day, .hour, .minute, .second], from: date)
        let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false)
        let request = UNNotificationRequest(identifier: identifier, content: notification, trigger: trigger)
        
        let center = UNUserNotificationCenter.current()
        center.add(request) { (error) in
            if error != nil {
                print("There was an error trying to send \(notification.title) notification")
            }
            
            print("Successfully sent \(notification.title) notification")
        }
}
  • Вопрос задан
  • 166 просмотров
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы