Handling applicationDidBeautive - "앱이 Active가 되었을 때 뷰 컨트롤러가 어떻게 응답할 수 있습니까?"
나는 가지고 있습니다.UIApplicationDelegate
메인 AppDelegate.m 클래스의 프로토콜과 함께applicationDidBecomeActive
메서드가 정의되었습니다.
응용 프로그램이 백그라운드에서 돌아오면 메소드를 호출하고 싶지만 메소드가 다른 뷰 컨트롤러에 있습니다.현재 표시 중인 뷰 컨트롤러를 확인하려면 어떻게 해야 합니까?applicationDidBecomeActive
메소드를 선택한 다음 해당 컨트롤러 내의 메소드를 호출하시겠습니까?
응용프로그램의 모든 클래스가 응용프로그램의 다른 알림에 대한 "관찰자"가 될 수 있습니다.보기 컨트롤러를 만들 때(또는 로드할 때) 해당 컨트롤러를 의 관찰자로 등록할 수 있습니다.UIApplicationDidBecomeActiveNotification
응용프로그램으로 알림을 보낼 때 호출할 메서드를 지정합니다.
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(someMethod:)
name:UIApplicationDidBecomeActiveNotification object:nil];
뒷정리를 하는 것을 잊지 마세요!시야가 멀어질 때는 관찰자 역할을 하지 않는 것을 잊지 마십시오.
[[NSNotificationCenter defaultCenter] removeObserver:self
name:UIApplicationDidBecomeActiveNotification
object:nil];
Notification Center에 대한 자세한 정보.
Swift 3, 4 동등:
관찰자 추가
NotificationCenter.default.addObserver(self,
selector: #selector(applicationDidBecomeActive),
name: .UIApplicationDidBecomeActive, // UIApplication.didBecomeActiveNotification for swift 4.2+
object: nil)
관찰자 제거
NotificationCenter.default.removeObserver(self,
name: .UIApplicationDidBecomeActive, // UIApplication.didBecomeActiveNotification for swift 4.2+
object: nil)
콜백
@objc func applicationDidBecomeActive() {
// handle event
}
Swift 2 동등물:
let notificationCenter = NSNotificationCenter.defaultCenter()
// Add observer:
notificationCenter.addObserver(self,
selector:Selector("applicationWillResignActiveNotification"),
name:UIApplicationWillResignActiveNotification,
object:nil)
// Remove observer:
notificationCenter.removeObserver(self,
name:UIApplicationWillResignActiveNotification,
object:nil)
// Remove all observer for all notifications:
notificationCenter.removeObserver(self)
// Callback:
func applicationWillResignActiveNotification() {
// Handle application will resign notification event.
}
스위프트 5
fileprivate func addObservers() {
NotificationCenter.default.addObserver(self,
selector: #selector(applicationDidBecomeActive),
name: UIApplication.didBecomeActiveNotification,
object: nil)
}
fileprivate func removeObservers() {
NotificationCenter.default.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil)
}
@objc fileprivate func applicationDidBecomeActive() {
// here do your work
}
스위프트 4.2
관찰자 추가-
NotificationCenter.default.addObserver(self, selector: #selector(handleEvent), name: UIApplication.didBecomeActiveNotification, object: nil)
관찰자 제거-
NotificationCenter.default.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil)
이벤트 처리
@objc func handleEvent() {
}
Swift 4와 함께, Apple은 새로운 컴파일러 경고를 통해 사용을 피한다고 조언합니다.#selector
이 경우에는이를 위해 훨씬 안전한 방법은 다음과 같습니다.
먼저 관찰자 인스턴스(취소에 사용)를 유지할 변수를 만듭니다.
var didBecomeActiveObserver: NSObjectProtocol
그런 다음 알림에서 사용할 수 있는 유휴 변수를 만듭니다.
lazy var didBecomeActive: (Notification) -> Void = { [weak self] _ in
// Do stuff
}
실제 알림을 포함해야 하는 경우에는 다음을 교체하십시오._
와 함께notification
.
다음으로, 앱이 활성화되는 것을 관찰하기 위해 알림을 설정합니다.
func setupObserver() {
didBecomeActiveObserver = NotificationCenter.default.addObserver(
forName: UIApplication.didBecomeActiveNotification,
object: nil,
queue:.main,
using: didBecomeActive)
}
여기서 큰 변화는 전화를 거는 대신#selector
이제 위에 생성된 변수를 var라고 부릅니다.이렇게 하면 잘못된 선택기 충돌이 발생하는 상황을 없앨 수 있습니다.
마지막으로 관찰자를 제거합니다.
func removeObserver() {
NotificationCenter.default.removeObserver(didBecomeActiveObserver)
}
Swift 5 버전:
NotificationCenter.default.addObserver(self,
selector: #selector(loadData),
name: UIApplication.didBecomeActiveNotification,
object: nil)
iOS 9 이상에서는 더 이상 관찰자를 제거할 필요가 없습니다.
인 스위프트 5
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
NotificationCenter.default.addObserver(self, selector: #selector(applicationWillResignActive), name: UIApplication.willResignActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
NotificationCenter.default.removeObserver(self, name: UIApplication.willResignActiveNotification, object: nil)
NotificationCenter.default.removeObserver(self, name: UIApplication.didBecomeActiveNotification, object: nil)
}
@objc private func applicationWillResignActive() {
}
@objc private func applicationDidBecomeActive() {
}
결합 방법:
import Combine
var cancellables = Set<AnyCancellable>()
NotificationCenter.default.publisher(for: UIApplication.didBecomeActiveNotification)
.sink { notification in
// do stuff
}.store(in: &cancellables)
Cleaner Swift 5+ 솔루션
관찰자 추가init
또는viewDidLoad
:
NotificationCenter.default.addObserver(self,
selector: #selector(appDidBecomeActive),
name: UIApplication.didBecomeActiveNotification,
object: nil)
다른 답변처럼 관찰자를 제거할 필요는 없습니다.자동으로 수행됩니다.
@objc private func appDidBecomeActive() {
// do your magic
}
스위프트를 사용하는 사람이 있다면,UI:
.onReceive(NotificationCenter.default.publisher(
for: UIApplication.didBecomeActiveNotification)) { _ in
print("DID BECOME ACTIVE")
}
)
Swift5 MacOS의 경우 UIA 애플리케이션 대신 NSA 애플리케이션을 사용해야 합니다.
NotificationCenter.default.addObserver(self,
selector: #selector(applicationDidBecomeActive),
name: (NSApplication.didBecomeActiveNotification),
object: nil)
}
언급URL : https://stackoverflow.com/questions/3639859/handling-applicationdidbecomeactive-how-can-a-view-controller-respond-to-the
'programing' 카테고리의 다른 글
Sqlite DB가 Azure Dotnet 핵심 엔터티 프레임워크에서 잠김 (0) | 2023.06.07 |
---|---|
매개 변수를 사용하는 Bash 별칭을 만드시겠습니까? (0) | 2023.06.07 |
C(char, int)에서 포인터 교환 (0) | 2023.06.07 |
Firestore 보안 규칙: 문서에서 배열에서 사용자 ID 검색 (0) | 2023.06.07 |
GCC에 대한 "-Wl, option"과 "-Xlinker option" 구문 사이에 차이점이 있습니까? (0) | 2023.06.07 |