How to check the date everyday in swiftUI

Viewed 459

I am new to the swiftUI. Right now, I am making an app that takes down your task progress. In the app, I need to refill the list with goals of user have every day (I guess 12 AM), where and how do I check the time in swift? I know that we could use app delegate in storyboard, but for SwiftUI, after applying CoreData Manager, the app delegate has gone and we have app.swift instead, where should I do the checking now? Thank you!

2 Answers

Building off of Leo Dabus' suggestion to watch for NSCalendarDayChanged notifications here's some code showing how that can be done in SwiftUI.

import SwiftUI

struct ContentView: View {

    @ObservedObject var viewModel = ContentViewModel()

    var body: some View {
        VStack {
            Text(viewModel.displayDate)
            // List of goals
        }
    }
}

class ContentViewModel: ObservableObject {

    @Published var currentDate: Date = Date()

    var displayDate: String {
        Self.simpleDateFormatter.string(from: currentDate)
    }

    private static let simpleDateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "MMMM d"
        return formatter
    }()

    init() {
        NotificationCenter.default.addObserver(self, selector: #selector(dayDidChange), name: .NSCalendarDayChanged, object: nil)
    }

    @objc
    func dayDidChange() {
        currentDate = Date()
    }
}
  1. You can use - (void)applicationSignificantTimeChange:(UIApplication *)application; in AppDelegate to monitor such changes.

  2. You can also register for a notification in AppDelegate UIApplication.significantTimeChangeNotification iOS will call both the registered notification method as well above delegate method.

       NotificationCenter.default.addObserver(self, selector: #selector(timeChanged), name: UIApplication.significantTimeChangeNotification , object: nil)
 @objc func timeChanged() {
        print("App Time Changed")
    }
  1. In case you want to hook up with your SwiftUI directly, you can register your Swift view with your publisher. Publisher will listen for notification name UIApplication.significantTimeChangeNotification.

Either of the ways can be used based on your requirement.

struct ContentView: View {
    @State var dayDetails: String = "Hello World"
    var body: some View {
        Text(dayDetails)
            .padding().onReceive(NotificationCenter.default.publisher(for: UIApplication.significantTimeChangeNotification), perform: { _ in
                dayDetails = "Day has changed"
            })
    }
}

Related