0
import Foundation
import SwiftUI
import UserNotifications

class NotificationHandler: ObservableObject {
    @Published var notificationCounter = 0
    func askPermission() {
        UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { success, error in
            if success {
                print("Access granted!")
            }
            else if let error = error {
                print(error.localizedDescription)
            }
        }
    }
}

struct SendNotificationView: View {
    @State var notificationTitle = ""
    @State var notificationMessage = ""
    @StateObject var notificationHandler = NotificationHandler()
    var body: some View{
        VStack{
            Text("Заголовок")
            TextField("введите название заголовка", text: $notificationTitle)
            Text("Сообщение")
            TextField("введите сообщение", text: $notificationMessage)
           
            Button(action: {
                sendNotification(title: notificationTitle, message: notificationMessage)
                self.notificationHandler.notificationCounter += 1
            }) {
                ZStack {
                    RoundedRectangle(cornerRadius: CGFloat(10))
                        .frame(maxWidth: .infinity, maxHeight: 50, alignment: .center)
                        .padding(.horizontal, 100)
                        .foregroundColor(Color("3"))
                    Text("Отправить").foregroundColor(.blue)
                }
            }
            Text("\(notificationHandler.notificationCounter)")
            
        } .environmentObject(notificationHandler)
    }
    func sendNotification(title: String, message: String) {
        let content = UNMutableNotificationContent()
        content.title = title
        content.subtitle = message
        content.sound = UNNotificationSound.default

        // show this notification five seconds from now
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)

        // choose a random identifier
        let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)

        // add our notification request
        UNUserNotificationCenter.current().add(request)
    }
}

struct HomeView: View {

    @EnvironmentObject var notificationHandler: NotificationHandler
    
    init() {
        let appearance = UINavigationBarAppearance()
        appearance.shadowColor = .clear
        UINavigationBar.appearance().standardAppearance = appearance
        UINavigationBar.appearance().scrollEdgeAppearance = appearance
    }
    var body: some View {
        NavigationView {
            ScrollView {
                HStack{}
                    .navigationBarTitle("Wellness Club", displayMode: .inline)
                    .navigationBarItems(trailing:
                                            Button(action: {
                    //code
                    }) {ZStack {
                        Image(systemName: "bell")
                            .foregroundColor(Color("gold"))
                        Circle()
                            .foregroundColor(Color("gold"))
                            .font(.system(size: 20))
                            .padding(.bottom, 17)
                            .padding(.leading, 12)
                        Text("\(notificationHandler.notificationCounter)") // THIS LINE IS CAUSING FATAL ERROR!!!
                            .foregroundColor(.white)
                            .font(.system(size: 10))
                            .padding(.bottom, 17)
                            .padding(.leading, 12)
                    }
                    })
                    .toolbar {
                        ToolbarItem(placement: .principal) {
                            Image("WellnessClub")
                                .resizable()
                                .aspectRatio(contentMode: .fit)
                        }
                    }
                 }
              }
          } 
}

When I run the application, I get a fatal error and the application crashes. I tried using this function in different ways, but in all cases I got the same result. when I tried to use the binding, I got an error. and yes, this is just part of the code. From what I tried, it was to put a function instead of a text that took integer values, but output a string of values . I also tried to use "switch-case". Still adding .environmentObject(SendNotificationView()) to ContentView but the result was the same

I want to avoid a fatal error

HangarRash
  • 7,314
  • 5
  • 5
  • 32

0 Answers0