iOS 응용 (swift)
[iOS - swift] NotificationCenter, RxSwift, Foreground진입 시 동작
jake-kim
2020. 11. 16. 22:37
Rx를 쓰지 않고 NotificationCenter를 이용한 방법은 여기 참고
NotificationCenter를 쓰는 경우
- 화면이 background에서 foreground로 변하는 경우
- AppDelegate에서 딥링크 처리시, 특정 화면에 event를 주입해주고 알림을 보내는 경우
사용준비
pod file에 아래 정보 입력 후 pod install
pod 'RxSwift'
pod 'RxCocoa'
기본 구조
(케이스: AppDelegate에서 home에 노티를 보내고 싶은 경우)
- NotificationCenter를 구별할 수 있는 key 정의 (타입은 NSNotification.Name(_ :String))
// Constants
extension NSNotification.Name {
static let home = NSNotification.Name("Home")
}
- 노티 전송 (주는 쪽)
// AppDelegate
NotificationCenter.default.post(name: .home, object: nil)
- 노티 관찰 (받는 쪽)
NotificationCenter.default.rx.notification(.home)
.asDriverOnErrorNever()
.drive(onNext: { [weak self] _ in
print("noti 수신")
}).disposed(by: bag)
Foreground에 진입 한 경우, 관찰 하는 법 (받는 쪽)
// myAppViewModel.swift
NotificationCenter.default.rx.notification(UIApplication.willEnterForegroundNotification)
.asDriver(onErrorRecover: { _ in .never()})
.drive(onNext: { [weak self] _ in
print("foreground 진입")
}).disposed(by: bag)