возникли проблемы с внедрением уведомлений в мое приложение будильника - PullRequest
0 голосов
/ 23 июня 2018

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

Существует функция triggerAlarm(), которая отслеживает время и проходит черезitems массив типа [Item]() (Item - это класс типа NSManagedObject, который сохраняет данные. Он имеет 2 атрибута time: String & isOn: Bool).

Проблема заключается в том, чточто метод Timer в viewDidLoad() не выполняется через этот цикл в triggerAlarm() func, а печатает realTime.Предполагается, что цикл сравнивает realTime с массивом items и вызывает функцию notificationTrigger(), если свойство isOn имеет значение true, но его не происходит.

Xcode также не отображает никаких ошибок.

Вот код:

import UIKit
import UserNotifications

class TableViewController: UITableViewController {

    var realTime  = String()
    var items     = [Item]()

    override func viewDidLoad() {
        super.viewDidLoad()
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: {didAllow, error in})

    }

    override func viewWillAppear(_ animated: Bool) {

        getData()
        tableView.reloadData()

    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }

    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) as! TableViewCell

        let row = items[indexPath.row]

        cell.timeLbl.text   = row.time
        cell.switchBtn.isOn = row.isOn

        cell.callback = { newValue in
            row.isOn = newValue
            (UIApplication.shared.delegate as! AppDelegate).saveContext()
        }
        return cell
    }

    func getData() {
        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
        do {
             items = try context.fetch(Item.fetchRequest())
        }catch{
            print("\(error)")
        }
    }

    func triggerAlarm() {
        realTime = DateFormatter.localizedString(from: Date(), dateStyle: .none, timeStyle: .short)
        print(realTime)
        for i in 0..<items.count {
            if (items[i].time!) == realTime && items[i].isOn == true{
                print(time)
                self.notificationTrigger()
            }else {
                return
            }
        }
    }

    func notificationTrigger() {
        let content      = UNMutableNotificationContent()
        content.title    = "time is up \(time)"
        content.subtitle = "asdf"
        content.body     = "qwer"
        content.badge    = 0

        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
        let request = UNNotificationRequest(identifier: "customNotification", content: content, trigger: trigger)
        UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)

    }
}

1 Ответ

0 голосов
/ 23 июня 2018
@objc func triggerAlarm() {
    realTime = DateFormatter.localizedString(from: Date(), dateStyle: .none, timeStyle: .short)
    print(realTime)
    for i in 0..<items.count {
        if (items[i].time!) == realTime && items[i].isOn == true{
            print(time)
            self.notificationTrigger()
        }else {
            return
        }
    }
}

Здесь вы используете return in else. Таким образом, вместо прерывания цикла для текущей итерации (я полагаю, вы хотите достичь этого), он возвращается из всего вызова метода.Вместо этого используйте: -

продолжить

Или лучше просто пропустить остальную часть

 @objc func triggerAlarm() {
    realTime = DateFormatter.localizedString(from: Date(), dateStyle: .none, timeStyle: .short)
    print(realTime)
    for i in 0..<items.count {
        if (items[i].time!) == realTime && items[i].isOn == true{
            print(time)
            self.notificationTrigger()
        }
    }
}
...