Как сделать локальные запланированные уведомления на Swift? - PullRequest
0 голосов
/ 28 марта 2020

Добрый день. Суть приложения: в указанные дату и время приложение должно «выбрасывать» локальные уведомления с определенными фразами. Фразы не перекрываются, поэтому вы не сможете их повторить. Как установить отдельное время и дату для каждого ключевого слова? Я новичок в Swift. Я пытаюсь понять. Но после гугля уже каша в голове. Согласно учебным пособиям, я сделал код, который работает, но работает с задержкой в ​​10 секунд. То есть после нажатия на кнопку через 10 секунд пу sh выбрасывается. Как сделать так, чтобы я просто устанавливал разные задержки (например, 3,6,9,12,15 часа для каждого ключевого слова) или перестраивал код для разделения каждого уведомления? Мне даже не нужно иметь все это одним нажатием кнопки. Вы просто входите в приложение, принимаете запрос на уведомления, и они приходят по часам. Вопрос может показаться очень глупым. Не судите строго. Прикрепленный код.

import UIKit
import UserNotifications

class ViewController: UIViewController {


@IBAction func sendNotification(sender: UIButton){
    scheduleNotification(inSeconds: 10) {(success) in
        if success {
            print("We send it")
        } else {
            print("Failed")
        }
    }
}

func scheduleNotification(inSeconds seconds:TimeInterval, completion: (Bool) -> ()) {

    removeNotification(withIdentifiers:["Bear"])

    let date = Date(timeIntervalSinceNow: seconds)
    print (Date())
    print(date)

    let content = UNMutableNotificationContent()
    content.title = "Текст"
    content.body = "Текст"
    content.sound = UNNotificationSound.default()

    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: "Bear", content: content, trigger: trigger)

    let center = UNUserNotificationCenter.current()
    center.add(request, withCompletionHandler: nil)

}






func removeNotification(withIdentifiers identifiers: [String]) {
    let center = UNUserNotificationCenter.current()
    center.removePendingNotificationRequests(withIdentifiers: identifiers)
}

deinit {
    removeNotification(withIdentifiers: ["Bear"])
}

}

1 Ответ

0 голосов
/ 28 марта 2020

Вы можете создать метод, который будет создавать все необходимые уведомления, а затем отправлять его через итерацию.

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": 3600, "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": 7200, "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")
    }
}
...