iOS开发实用技术程序员

iOS小笔记 | 通知开启关闭状态的监控

2019-01-17  本文已影响36人  Lol刀妹

类似于简书的通知管理页:

不同的是我这里是用的一个UISwitch来表示通知的开启关闭状态:

监听通知状态.gif

整个流程就是:

  1. 点击switch,跳转到设置页;
  2. 开启or关闭通知;
  3. 回到app,刷新switch状态。

1.关于switch

如果单纯的放一个UISwitch上去,用户点击,switch的状态切换动画会与跳转到系统设置页的转场动画同时执行,虽然很快,但还是可以看到switch的状态切换,我不想让switch的状态在这个时候改变。一个解决方案是在switch上放一个透明button,由button来处理用户事件,而switch只用于表示通知开闭状态:

- (UISwitch *)notifSwitch {
    if (!_notifSwitch) {
        _notifSwitch = [[UISwitch alloc] init];
        // 在switch上add一个透明button
        UIButton *button = [[UIButton alloc] initWithFrame:_notifSwitch.bounds];
        [_notifSwitch addSubview:button];
        [button addTarget:self action:@selector(switchButtonClicked) forControlEvents:UIControlEventTouchUpInside];
    }
    return _notifSwitch;
}

注:UISwitch的size是固定的:

// This class enforces a size appropriate for the control, and so the frame size is ignored.

2.跳转到设置页

- (void)switchButtonClicked {
    // 跳转到系统设置
    NSURL *settingURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
    if (@available(iOS 10.0, *)) {
        [[UIApplication sharedApplication] openURL:settingURL options:[NSDictionary dictionary] completionHandler:nil];
    } else {
        [[UIApplication sharedApplication] openURL:settingURL];
    }
}

两个跳转方法,一个是iOS10之前的,一个是iOS10之后的。

3.刷新switch

UIUserNotificationSettings *setting = [[UIApplication sharedApplication] currentUserNotificationSettings];
self.notifSwitch.on = (setting.types != UIUserNotificationTypeNone);

4.刷新时机

系统设置其实也是一个app,从你的app跳转到系统设置,app此时由前台进入后台;从系统设置回到你的app,app由后台进入前台。此时AppDelegate的applicationWillEnterForeground:会被调用。

系统提供了一个通知,标识APP将要进入前台:

UIKIT_EXTERN NSNotificationName const UIApplicationWillEnterForegroundNotification      NS_AVAILABLE_IOS(4_0);

所以可以通过监听这个通知来执行刷新:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshSwitch) name:UIApplicationWillEnterForegroundNotification object:nil];

整个过程就是这样的,如果你有更好的思路,欢迎分享。

上一篇下一篇

猜你喜欢

热点阅读