ใช้ Objective-C
คุณควรจะลงทะเบียนUIApplicationWillEnterForegroundNotificationในของคุณViewController's viewDidLoadวิธีการและเมื่อใดก็ตามที่แอปจะกลับมาจากพื้นหลังที่คุณสามารถทำสิ่งที่คุณต้องการจะทำในวิธีการลงทะเบียนสำหรับการแจ้งเตือน ViewController' viewWillAppear ' หรือviewDidAppearจะไม่ถูกเรียกเมื่อแอปกลับมาจากพื้นหลังเป็นพื้นหน้า
-(void)viewDidLoad{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(doYourStuff)
name:UIApplicationWillEnterForegroundNotification object:nil];
}
-(void)doYourStuff{
// do whatever you want to do when app comes back from background.
}
อย่าลืมยกเลิกการลงทะเบียนการแจ้งเตือนที่คุณลงทะเบียนไว้
-(void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
หมายเหตุหากคุณลงทะเบียนviewControllerสำหรับUIApplicationDidBecomeActiveNotificationวิธีการของคุณจะถูกเรียกทุกครั้งที่แอปของคุณเปิดใช้งานไม่แนะนำให้ลงทะเบียนviewControllerสำหรับการแจ้งเตือนนี้
ใช้สวิฟท์
สำหรับการเพิ่มผู้สังเกตการณ์คุณสามารถใช้รหัสต่อไปนี้
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: "doYourStuff", name: UIApplication.willEnterForegroundNotification, object: nil)
}
func doYourStuff(){
// your code
}
ในการลบผู้สังเกตการณ์คุณสามารถใช้ฟังก์ชัน deinit ของ swift
deinit {
NotificationCenter.default.removeObserver(self)
}