@Bear027

Почему мне не приходят локальные уведомления Swift?

Доброго дня! Не могу понять, почему мне не приходят локальные уведомления? Один пользователь stackoverflow помог мне собрать этот код, что бы разные локальные уведомления приходили с задержкой. Что в нем не так, и что нужно доделать? Не могли бы Вы помочь исправить это. Я новичок. Код из ViewController и AppDelegate прилагаю.

/
    //  ViewController.swift
    //  bee
    //
    //  Created by Rodion Bizyaev on 22.02.2020.
    //  Copyright © 2020 Rodion Bizyaev. All rights reserved.
    //
    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")
            }
    }



    //  AppDelegate.swift
    //  bee
    //
    //  Created by Rodion Bizyaev on 22.02.2020.
    //  Copyright © 2020 Rodion Bizyaev. All rights reserved.
    //
    import UIKit
    import UserNotifications
    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate {
        var window: UIWindow?
        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

            let center = UNUserNotificationCenter.current()
            center.requestAuthorization(options:[.alert, .sound] )
            { (granted, error) in
            }
            return true
        }

        func applicationWillResignActive(_ application: UIApplication) {
            // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
            // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
        }

        func applicationDidEnterBackground(_ application: UIApplication) {
            // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
            // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
        }

        func applicationWillEnterForeground(_ application: UIApplication) {
            // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
        }

        func applicationDidBecomeActive(_ application: UIApplication) {
            // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
        }

        func applicationWillTerminate(_ application: UIApplication) {
            // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        }

    }
  • Вопрос задан
  • 78 просмотров
Решения вопроса 1
IvanVorobei
@IvanVorobei
iOS разработчик, ещё интерфейсы дизайню
Нет вызова prepareAndSendLocalNotifications.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

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

Войти через центр авторизации
Похожие вопросы
Почта Банк Москва
от 170 000 до 230 000 ₽
SLEKI Санкт-Петербург
от 100 000 до 200 000 ₽
от 100 000 ₽
07 июн. 2020, в 03:38
1000 руб./за проект
07 июн. 2020, в 01:42
300000 руб./за проект