Jes*_*ack 163
当应用程序进入后台接收通知时,您可以让任何课程感兴趣.这是将这些类与AppDelegate耦合的一个很好的替代方法.
初始化所述类时:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillTerminate:) name:UIApplicationWillTerminateNotification object:nil];
Run Code Online (Sandbox Code Playgroud)
回应通知
-(void)appWillResignActive:(NSNotification*)note
{
}
-(void)appWillTerminate:(NSNotification*)note
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillResignActiveNotification object:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillTerminateNotification object:nil];
}
Run Code Online (Sandbox Code Playgroud)
Ash*_*k R 24
在Swift 4.0中
override func viewDidLoad() {
super.viewDidLoad()
let app = UIApplication.shared
//Register for the applicationWillResignActive anywhere in your app.
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.applicationWillResignActive(notification:)), name: NSNotification.Name.UIApplicationWillResignActive, object: app)
}
@objc func applicationWillResignActive(notification: NSNotification) {
}
Run Code Online (Sandbox Code Playgroud)
Dam*_*ien 10
在您的应用程序AppDelegate上,该(void)applicationDidEnterBackground:(UIApplication *)application方法将由iOS调用.你可以在那里停下你的计时器.
对于那些希望在Swift中执行此操作的人:
上init:
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(applicationWillResignActive), name: UIApplicationWillResignActiveNotification, object: nil)
Run Code Online (Sandbox Code Playgroud)
上deinit:
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationWillResignActiveNotification, object: nil)
Run Code Online (Sandbox Code Playgroud)
回应通知:
dynamic private func applicationWillResignActive() {
// Do things here
}
Run Code Online (Sandbox Code Playgroud)
Apple鼓励我们尽可能避免在Swift中使用动态调度和Objective-C选择器,但这仍然是最方便的方法.
| 归档时间: |
|
| 查看次数: |
65475 次 |
| 最近记录: |