Swift SwiftUI上でUIKit使用、アプリバッググランド遷移をUIKit側に通知

2021年8月19日

NotificationCenterで通知

SwiftUI側

import SwiftUI

struct MainView: View {
    @Environment(\.scenePhase) private var scenePhase
    
    var body: some View {
        RefillView()
            .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側

:
:
    override func viewDidLoad() {
        super.viewDidLoad()

        NotificationCenter.default.addObserver(self, selector: #selector(aplBackGround(notification:)), name: .aplBackGround, object: nil)
    }
    
    @objc func aplBackGround(notification: NSNotification?) {
        print(#function)
    }
:
:

SwiftSwift,SwiftUI

Posted by shi-n