2014-07-23 22 views
9

Tôi có một tình huống trong đó tôi phải intialize một đối tượng mỗi khi nó xuất phát từ nền sang nền trước và phải sử dụng NSNotificationCenter không có appdelegate vì iam xây dựng một static thư viện vì vậy sẽ không được appdelegate với điều đó vì vậy hãy giúp tôi trong cùng một.iOS NSNotificationCenter để kiểm tra xem ứng dụng có xuất phát từ nền sang nền trước

Trả lời

16

Bạn đã thử UIApplicationWillEnterForegroundNotification chưa?

Ứng dụng cũng đăng thông báo UIApplicationWillEnterForegroundNotification ngay trước khi gọi applicationWillEnterForeground: để cung cấp cho các đối tượng quan tâm cơ hội phản hồi chuyển tiếp.

Theo dõi thông báo:

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

Thực hiện một mã số, mà cần phải được gọi là:

- (void) yourUpdateMethodGoesHere:(NSNotification *) note { 
// code 
} 

Đừng quên để bỏ đăng ký:

3 phiên bản
[[NSNotificationCenter defaultCenter] removeObserver:self]; 
+0

bạn có thể gửi các đoạn mã iam nhầm lẫn – user3115014

+0

Kiểm tra này một: http://stackoverflow.com/questions/2191594/send-and-receive-messages-through- nsnotificationcenter-in-objective-c –

7

Swift

override func viewDidAppear(_ animated: Bool) { 
    super.viewDidAppear(animated) 
    NotificationCenter.default.addObserver(self, 
              selector:#selector(applicationWillEnterForeground(_:)), 
              name:NSNotification.Name.UIApplicationWillEnterForeground, 
              object: nil) 
} 

override func viewWillDisappear(_ animated: Bool) { 
    super.viewWillDisappear(animated) 
    NotificationCenter.default.removeObserver(self) 
} 

func applicationWillEnterForeground(_ notification: NSNotification) { 
    .... 
} 

bạn cũng có thể sử dụng NSNotification.Name.UIApplicationDidBecomeActive

Các vấn đề liên quan