I have a function that checks whether the user has enabled their push notification/ notification alert in the iphone. If the user has turned on their notification, it will print true in the swift view, and if the user has turned off their notification, it will print false.
I could achieve this using the stated below function and gives relevant output. But, this is not real-time. I have to close and re-open the app to reflect current changes. Im looking way to give true/false real-time and async using publisher and subscriber which show status realtime in my app
My code :-
var isRegister : Bool = false
func isEnabled() -> Bool {
let center = UNUserNotificationCenter.current()
center.getNotificationSettings { (settings) in
if(settings.authorizationStatus == .authorized) {
isRegister = true
print("Push notification is enabled")
} else {
isRegister = false
print("Push notification is not enabled")
}
}
return isRegister
}
CodePudding user response:
there are a delay in getting authorization status of notification
so you should have to use completion
func authorizeStatus(completion: @escaping (_ isAuthorized: Bool) -> Void) {
let center = UNUserNotificationCenter.current()
center.getNotificationSettings { (settings) in
if(settings.authorizationStatus == .authorized) {
completion(true)
print("Push notification is enabled")
} else {
completion(false)
print("Push notification is not enabled")
}
}
}
and how to check
override func viewDidLoad() {
super.viewDidLoad()
authorizeStatus { isAuthorized in
print(isAuthorized)
}
}
and if you want check status when click on Allow or Cancel of Notification Alert you can check it as follow
UNUserNotificationCenter.current().requestAuthorization(options: [ .sound, .badge]) { (success, error) in
if let error = error {
print("Request Authorization Failed (\(error), \(error.localizedDescription))")
}
else{
print(success) // check here
if success {
print("you enable it")
} else {
print("you cancel it")
}
}
}
how to check in swift ui
var body: some View {
VStack {
.onAppear { self. authorizeStatus { isAuthorized in
print(isAuthorized)
}
}
}
CodePudding user response:
how to check in swift ui
var body: some View {
VStack {
.onAppear { self. authorizeStatus { isAuthorized in
print(isAuthorized)
}
}
}
Im trying to add text componenet to display text in my app. These solution does display in the log of xcode but no in the app. There is no way to use Text() as its bool value.
Any way to display text message on the screen directly and in the realtime