The following code inside an newly created iOS App project results in the following warning:
Non-sendable type 'Notification?' returned by call from main actor-isolated context to non-isolated instance method 'next()' cannot cross actor boundary
import SwiftUI
struct ContentView: View {
var body: some View {
VStack {
Image(systemName: "globe")
.imageScale(.large)
.foregroundColor(.accentColor)
Text("Hello, world!")
}
.padding()
.task{
for await _ in NotificationCenter.default.notifications(named: UIDevice.orientationDidChangeNotification){
print("orientation changed")
}
}
}
}
What is the correct way to handle this or is it an API error?
Isn't NotificationCenter.default.notifications(named: ...)
exactly meant to be used with for ... await
aka. next()
?
Many Foundation types that are ‘obviously’ sendable can’t be marked as sendable. There are two commons reasons for this:
-
Subclassing
-
User info dictionaries
For example, Notification
can’t be sendable because it has a user info dictionary and that might contain a non-sendable value.
The best way to handle that varies based on the context. In the specific example that you posted at the top of this thread, you can change the code to look like this:
for await _ in NotificationCenter.default.notifications(named: UIDevice.orientationDidChangeNotification).map( { $0.name } ) {
print("orientation changed")
}
This maps the async sequence of notifications to an async sequence of notification names, and those are sendable.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"