developer tip

앱이 내 뷰의 백그라운드로 들어갈 때를 감지하는 가장 좋은 방법은 무엇입니까?

optionbox 2020. 10. 28. 08:02
반응형

앱이 내 뷰의 백그라운드로 들어갈 때를 감지하는 가장 좋은 방법은 무엇입니까?


NSTimer일부 코드를 실행 하는 데 사용하는 뷰 컨트롤러가 있습니다.

타이머를 일시 중지 할 수 있도록 앱이 백그라운드로 이동하는시기를 감지하는 가장 좋은 방법은 무엇입니까?


앱이 백그라운드로 전환 될 때 관심있는 모든 클래스가 알림을 받도록 할 수 있습니다. 이는 이러한 클래스를 AppDelegate와 결합하는 좋은 대안입니다.

상기 클래스를 초기화 할 때 :

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillResignActive:) name:UIApplicationWillResignActiveNotification object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillTerminate:) name:UIApplicationWillTerminateNotification object:nil];

알림에 응답

-(void)appWillResignActive:(NSNotification*)note
{

}
-(void)appWillTerminate:(NSNotification*)note
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillResignActiveNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIApplicationWillTerminateNotification object:nil];

}

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) {

}

애플리케이션 AppDelegate에서 (void)applicationDidEnterBackground:(UIApplication *)application메소드는 iOS에 의해 호출됩니다. 거기에서 타이머를 멈출 수 있습니다.


Swift에서이 작업을 수행하려는 경우 :

켜짐 init:

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(applicationWillResignActive), name: UIApplicationWillResignActiveNotification, object: nil)

켜짐 deinit:

NSNotificationCenter.defaultCenter().removeObserver(self, name: UIApplicationWillResignActiveNotification, object: nil)

알림에 대한 응답 :

dynamic private func applicationWillResignActive() {
    // Do things here
}

Apple은 Swift에서 가능할 때마다 동적 디스패치 및 Objective-C 선택기를 피할 것을 권장하지만 이것이 여전히 가장 편리한 방법입니다.


신속한 4.1에서 :

클로저 버전을 사용합니다.

var observer: NSObjectProtocol!

// inside init or viewDidLoad:
observer = NotificationCenter.default.addObserver(forName: .UIApplicationWillResignActive, object: nil, queue: nil) { _ in
    print("willResignActive")
}

deinit {
    NotificationCenter.default.removeObserver(observer)
}

addObserver메서드는 특정 지점에서 제거해야하는 불투명 한 개체를 반환합니다.


- (void)applicationWillResignActive:(UIApplication *)application앱 델리게이트에서. UIApplicationWillResignActiveNotification다른 개체에 대한 알림을 등록 할 수도 있습니다.

하지만 반드시 타이머를 일시 중지 할 필요는 없습니다. 아무것도하지 않으면 앱이 잠자기 상태가되어 코드를 실행하지 않습니다. 아마 당신이 다시 활성화되면 타이머가 작동 할 것입니다. 특별한 일을해야한다면 등록 할 수있는 델리게이트 메소드와 알림이 있습니다.


only a side note: If you register a controller A to be notified going background, be careful that it will be called even if you (for example..) push a second controller B and You are displaying B: If this behaviour is not correct, is better to register/unregister in

didAppear/WillDisappear.


Swift 4:

init() {
    NotificationCenter.default.addObserver(self,
                                           selector: #selector(applicationWillResignActive),
                                           name: NSNotification.Name.UIApplicationWillResignActive,
                                           object: nil)
}

deinit {
    NotificationCenter.default.removeObserver(self,
                                              name: NSNotification.Name.UIApplicationWillResignActive,
                                              object: nil)
}

@objc private func applicationWillResignActive() {
    self.header.blur.effect = nil
}

참고URL : https://stackoverflow.com/questions/9011868/whats-the-best-way-to-detect-when-the-app-is-entering-the-background-for-my-vie

반응형