我实现了一个具有以下要求的ViewController:如果用户在15分钟后返回应用程序,视图应该重新加载数据。
我正在考虑使用viewDidDisappear
来保存应用程序转到后台时的时间戳,viewDidAppear
用于检查以前保存的值并在需要时刷新,但在切换应用程序时不会调用此方法
如何以简单的方式解决这个问题?
答案 0 :(得分:7)
使用UIApplicationDidBecomeActive
表示简历,UIApplicationWillResignActive
表示处理后台
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationWillResignActive, object: nil)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(self.closeActivityController), name: NSNotification.Name.UIApplicationWillResignActive, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.openactivity), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
}
并将该方法处理为
func closeActivityController() {
}
func openactivity() {
//view should reload the data.
}
其他通知类型
extension NSNotification.Name {
@available(iOS 4.0, *)
public static let UIApplicationDidEnterBackground: NSNotification.Name
@available(iOS 4.0, *)
public static let UIApplicationWillEnterForeground: NSNotification.Name
public static let UIApplicationDidFinishLaunching: NSNotification.Name
public static let UIApplicationDidBecomeActive: NSNotification.Name
public static let UIApplicationWillResignActive: NSNotification.Name
public static let UIApplicationDidReceiveMemoryWarning: NSNotification.Name
public static let UIApplicationWillTerminate: NSNotification.Name
}
答案 1 :(得分:6)
快捷键5
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(appMovedToBackground), name: UIApplication.willResignActiveNotification, object: nil)
notificationCenter.addObserver(self, selector: #selector(appBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
方法:
@objc func appMovedToBackground() {
print("App moved to background!")
}
@objc func appBecomeActive() {
print("App become active")
}
删除观察者
override func viewWillDisappear(_ animated: Bool) {
let notificationCenter = NotificationCenter.default
notificationCenter.removeObserver(self, name:UIApplication.willResignActiveNotification, object: nil)
notificationCenter.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil)
}
答案 2 :(得分:0)
UIApplicationDelegate
有以下两个功能:
applicationDidEnterBackground(_:)
applicationDidBecomeActive(_:)
这些可能就是你所需要的。