在我的方案中,用户将收到有关在应用程序中接收通知的警报。如果用户点击"不允许" UILabel更新为"未启用"。如果用户想要更改通知,则用户将导航到应用程序设置页面以更改通知权限状态。
func checkNotificationPermission(){
UNUserNotificationCenter.current().requestAuthorization(options:[.badge, .alert, .sound]){
(granted, error) in
if granted == true {
DispatchQueue.main.async {
print("notificaation access true")
self.notificationAccessLbl?.text = "Enabled"
}
}
else {
DispatchQueue.main.async {
self.notificationAccessLbl?.text = "Not enabled"
}
}
}
UIApplication.shared.registerForRemoteNotifications() }
但是当用户回到应用程序时,当用户从设置页面进入应用程序时,UILabel没有得到更新。
用于在用户从设置页面到应用程序后更新应用程序中的UILabel。我打电话了
func checkNotificationPermission()
更新ViewDidAppear()
方法中的UILabel值,然后在applicationwillbecomeactive method()
中注册一个函数。请帮助我。
答案 0 :(得分:2)
我在应用程序中切换设置页面,允许用户启用禁用推送,并且将在服务器上发送,但在该用户必须允许从设备的设置页面推送之前。这是我的解决方案
我创建了全局对象
var isPushEnabledFromSettings = false {
didSet {
// you can set label value here in main queue
}
}
和一种检查方法
func isPushPermissionGiven (permission:@escaping (Bool) -> ()) {
if #available(iOS 10.0, *) {
let current = UNUserNotificationCenter.current()
current.getNotificationSettings(completionHandler: {settings in
switch settings.authorizationStatus {
case .notDetermined:
permission(false)
case .denied:
permission(false)
case .authorized:
permission(true)
}
})
} else {
// Fallback on earlier versions
if UIApplication.shared.isRegisteredForRemoteNotifications {
permission(true)
} else {
permission(false)
}
}
}
并且在视图中确实加载了这些行
self.isPushPermissionGiven { (permission) in
self.isPushEnabledFromSettings = permission
}
NotificationCenter.default.addObserver(forName: NSNotification.Name.UIApplicationDidBecomeActive, object: nil, queue: .main) {[weak self] (notificaiont) in
guard let strongSelf = self else {return }
strongSelf.isPushPermissionGiven { (permission) in
DispatchQueue.main.async {
strongSelf.isPushEnabledFromSettings = permission
}
}
}
现在我已切换设置页面,允许用户启用禁用推送
@objc func switchChanged (sender:UISwitch) {
guard self.isPushEnabledFromSettings else {
AppDelegate.sharedDelegate.navigateUesrToSettings(withMessage: "Please grant push permission from settings")
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
sender.setOn(false, animated: false)
})
return
}
}
func navigateUesrToSettings (withTitle title:String = "YourApp", withMessage message:String) {
let alertController = UIAlertController (title: title, message: message, preferredStyle: .alert)
let settingsAction = UIAlertAction(title: "Settings", style: .default) { (_) -> Void in
guard let _ = URL(string: UIApplicationOpenSettingsURLString) else {
return
}
self.navigate(To: UIApplicationOpenSettingsURLString)
}
alertController.addAction(settingsAction)
let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: nil)
alertController.addAction(cancelAction)
AppDelegate.sharedDelegate.window?.rootViewController?.present(alertController, animated: true, completion: nil)
}
希望它对你有帮助:))