如何检查用户是否已从“设置”返回

How to check that user is back from Settings

我正在向我的用户发送本地通知,我想在通知设置按钮上显示相关标题。

如果关闭本地通知,则此标题应为 "Notifications: off",如果打开本地通知,则此标题应类似于 "Preferences"。

现在我正在 viewDidLoad 和 viewDidAppear 中检查它,它有效。

if UIApplication.sharedApplication().currentUserNotificationSettings()?.types.rawValue == 0 {
    //the first title
} else {
    //the second title
}

除了一种情况。如果我的用户将 phone 设置中的通知从 "on" 更改为 "off" 或相反,然后他又回来了——标题没有改变(因为这个 viewController已经加载并确实出现了)。

我如何检查用户是否已从“设置”返回?

当您的应用程序从非活动状态转到前台时,您可以观察到此通知,每次您的应用程序从后台再次打开时都会调用选择器:

输入viewDidLoad:

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(self.reloadData), name: UIApplicationWillEnterForegroundNotification, object: UIApplication.sharedApplication())

输入viewDidDissapeardeinit:

NSNotificationCenter.defaultCenter().removeObserver(self)

Swift 5.5:

NotificationCenter.default.addObserver(
    self,
    selector: #selector(yourFunction),
    name: UIApplication.willEnterForegroundNotification,
    object: UIApplication.shared
)

和:

deinit {
    NotificationCenter.default.removeObserver(self)
}