Swift SwiftUI上でUIKit使用、アプリバッググランド遷移をUIKit側に通知、Combineにしてみた
記事「Swift SwiftUI上でUIKit使用、アプリバッググランド遷移をUIKit側に通知」をCombine対応
SwiftUI側
前回記事から変わらず。
import SwiftUI
struct MainView: View {
var body: some View {
ExampleView()
.onAppear() {
RefillData.loadRefillImage()
}
.onChange(of: scenePhase, perform: { value in
switch(value) {
case .active:
print("active")
case .background:
print("background")
NotificationCenter.default.post(name: .aplBackGround, object: nil)
case .inactive:
print("inactive")
@unknown default:
print("default")
}
})
}
}
struct MainView_Previews: PreviewProvider {
static var previews: some View {
MainView()
}
}
extension Notification.Name {
static let aplBackGround = Notification.Name("aplBackGround")
}
UIKit側
・NotificationCenter.default.publisher().sink()に変更
・「private var cancellable: AnyCancellable?」ローカル変数にすると動きません
class ExampleController: UIViewController {
:
:
private var cancellable: AnyCancellable?
:
:
override func viewDidLoad() {
super.viewDidLoad()
self.cancellable = NotificationCenter.default.publisher(for: .aplBackGround, object: nil).sink() { notification in
print(#function + ":to BackGround.")
}
}
:
:





