根据用户决定取消选中开关

Unchecking a switch depending on user decision

我正在构建一个应用程序,当用户启用开关时,它会询问用户是否允许 post 通知。我正在使用此代码:

- (IBAction)mySwitchValueChanged:(id)sender {
if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]){
    [[UIApplication sharedApplication] registerUserNotificationSettings:[UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]]; // ask the user for permission
}

if ([[UIApplication sharedApplication] respondsToSelector:@selector(currentUserNotificationSettings)]) { // Check it's iOS 8 and above
    UIUserNotificationSettings *grantedSettings = [[UIApplication sharedApplication] currentUserNotificationSettings];
    if (grantedSettings.types != UIUserNotificationTypeNone)
    {
        // Accepted
    } else
    {
        [self.mySwitch setOn:NO]; // Declined
    }
}
}

期望的行为如下:

当前行为使代码 运行 立即通过,不等待用户决定。我怎样才能改变它以获得所需的行为?

谢谢!

注意:这是解决方法

调用此方法后:- [UIApplication sharedApplication] registerUserNotificationSettings 并且用户为应用程序授予推送通知,然后 AppDelegate 中的 didRegisterForRemoteNotificationsWithDeviceToken 被解雇,

    - (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
  //call a notification when user granted Push Notifiaction 
   [[NSNotificationCenter defaultCenter] 
    postNotificationName:@"PushNotificationSuccess" 
    object:self];

}

所以你必须做的,你可以从提到的方法调用 NSNotification,相应地更新 UI。

- (void)updateUIOnNotification:(NSNotification *) notification
{

            // Accepted
   }
    //Call the below method in your else part and remove the line
    //[self.mySwitch setOn:NO];

    -(void)Showalert{
    UIAlertview*Temp=[[UIAlertview alloc]initWithTitle:@"Need Permission to Send Notifications" message:@"The App Wants The Permission to Work Properly!\nPermit The App in Notification settings"delegate:self cancelButtonTitle:@"Okay!" otherButtonTitles:nil];
     [Temp show];        
    }
    #pragma mark Alertview delegate method
    - (void)alertViewCancel:(UIAlertView *)alertView{
    //Remove the Below line From Else part of your code
      [self.mySwitch setOn:NO];
    }