LoginSignup
1
1

More than 1 year has passed since last update.

SwiftUIのViewでNotificationCenterを監視する

Last updated at Posted at 2022-03-12

ViewでNotificationを受け取る方法です。

サクッと通知したい。タイミングに注意

Notification便利ですよね。SwiftUIで使うには以下です。
Viewが生成されるより前にpostされると、受信できないので注意です。

方法

post 発信する側

class Greetings:NSObject {
    override init() {
        super.init()
            NotificationCenter.default.post(name: NSNotification.greeting, object: self, userInfo: ["greeting":"Ciao mondo!"])
    }
}

extension NSNotification {
    static let greeting = NSNotification.Name.init("greeting")
}

observe 受信する側

struct ContentView: View {
    @State var greeting:String = "Hello, world!"
    var model = Greeting()
    var body: some View {
        Text(greeting)
            .padding()
            .onReceive(NotificationCenter.default.publisher(for: NSNotification.greeting)) { notification in
                if let greeting = notification.userInfo?["greeting"] as? String {
                    self.greeting = greeting
            }
        }         
    }
}

これだと、Viewに通知が反映されません。
なぜかというと、Viewより先にNotification元のクラスが作られて、Viewでオブザーブするよりも先にpostされているからです。
Timerで解消しました。

class Greetings:NSObject {
    override init() {
        super.init()
            Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { timer in
                NotificationCenter.default.post(name: NSNotification.greeting, object: self, userInfo: ["greeting":"Ciao mondo!"])
            }
    }
}

Timerを止めたい場合は、受信側のViewからクラスに通知する必要があるでしょう。

🐣


フリーランスエンジニアです。
お仕事のご相談こちらまで
rockyshikoku@gmail.com

Core MLやARKitを使ったアプリを作っています。
機械学習/AR関連の情報を発信しています。

Twitter
Medium
GitHub

相棒

note

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1