How does one add Codable conformance to a class that needs to be isolated to the MainActor?
For example, the following code gives compiler errors:
@MainActor final class MyClass: Codable {
var value: Int
enum CodingKeys: String, CodingKey {
case value
}
init(from decoder: Decoder) throws { // <-- Compiler error: Initializer 'init(from:)' isolated to global actor 'MainActor' can not satisfy corresponding requirement from protocol 'Decodable'
let data = try decoder.container(keyedBy: CodingKeys.self)
self.value = try data.decode(Int.self, forKey: .value)
}
func encode(to encoder: Encoder) throws { // <-- Compiler error: Instance method 'encode(to:)' isolated to global actor 'MainActor' can not satisfy corresponding requirement from protocol 'Encodable'
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(value, forKey: .value)
}
}
I'm definitely struggling to get my head around actors and @MainActor at the moment!
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
I'm trying to figure out the correct structure for a macOS document app using SwiftUI and Swift 5.5 concurrency features.
I want to demonstrate updating a document's data asynchronously, in a thread safe manner, with the ability to read / write the data to a file, also thread-safe and in the background. Yet I am struggling to:
write clean code - some of it looks inelegant at best, more like clunky, compared to my prior apps which used DispatchQueues etc
implement Codeable conformance for an actor
I'm seeking ideas, corrections and advice on how to improve on this. I've posted the full code over at GitHub, as I will only highlight some particular elements here. This is a minimum viable app, just for proof-of-concept purposes.
The app
The app displays a list of Records with a button to add more. It should be able to save and reload the list from a file.
Current approach / design
I've chosen the ReferenceFileDocument protocol for the Document type, as this is what I would use in a future app which has a more complex data structure. (i.e. I'm not planning on using a pure set of structs to hold a documents' data)
Document has a property content of type RecordsModelView representing the top-level data structure.
RecordsModelView is annotated with @MainActor to ensure any updates it receives will be processed on the main thread.
RecordsModelView has a property of type RecordsModel. This is an actor ensuring read/write of its array of Records are thread safe, but not coordinated via the MainActor for efficiency.
The app assumes that the func to add an item takes a long time, and hence runs it from with a Task. Although not demonstrated here, I am also making the assumption that addRecord maybe called from multiple background threads, so needs to be thread safe, hence the use of an actor.
The code compiles and runs allowing new items to be added to the list but...
Issues
Firstly, I can't annotate Document with @MainActor - generates compiler errors I cannot resolve. If I could I think it might solve some of my issues...
Secondly, I therefore have a clunky way for Document to initialise its content property (which also has to be optional to make it work). This looks nasty, and has the knock on effect of needing to unwrap it everywhere it is referenced:
final class Document: ReferenceFileDocument {
@Published var content: RecordsViewModel?
init() {
Task { await MainActor.run { self.content = RecordsViewModel() } }
}
// Other code here
}
Finally, I can't get the RecordsModel to conform to Encodable. I've tried making encode(to encoder: Encoder) async, but this does not resolve the issue. At present, therefore RecordsModel is just conformed to Decodable.
func encode(to encoder: Encoder) async throws { // <-- Actor-isolated instance method 'encode(to:)' cannot be used to satisfy a protocol requirement
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(records, forKey: .records)
}
I am writing an App with both Mac and iPad versions that saves its state to a file. The user can store the file in their iCloud and open it both on the Mac and iPad simultaneously. If an update is made on either device the other will update their state to match.
This has been achieved using an NSFilePresenter / NSFileCoordinator approach. Both platforms are using identical code.
At present when I make a change on the iPad, a few moments later the Mac updates as expected.
However, this does not happen the other way around. If I update the data on the Mac the iPad never appears to receive an update.
I've tried this on the simulator also. I get similar behaviour, but can get the iPad to update it I use the simulator's Sync With iCloud function.
Any ideas of what I may be doing wrong - as clearly the code works in one direction!
Topic:
App & System Services
SubTopic:
General
Tags:
Files and Storage
Swift
Foundation
iCloud Drive
When I run my code with TSAN enabled I am getting an EXC_BAD_ACCESS exception thrown.
I am seeing the following error in debug navigator:
#0 0x0000000104becb44 in __tsan::ThreadClock::release(__tsan::DenseSlabAllocCache*, __tsan::SyncClock*) ()
The stack trace is not in my code.
Without TSAN I am seeing the following in the console:
(Fig) signalled err=-16993
Anybody seen this before?
This is under the new Beta 6 Xcode running under Ventura 13.0 Beta (22A5331f), on an M1 Mac.
Topic:
Programming Languages
SubTopic:
Swift
Tags:
Swift
Xcode Sanitizers and Runtime Issues
Concurrency
I'm writing a photo management app where the document stores the location of folders (in which image files reside). These are added by the user, and saved as security scoped bookmarks. All this appeared to be working.
However, I tested a use-case where the user starts working on one machine where they add a folder, which resides on an external drive. This works, as long as they remain the on the same machine.
However, if they move to another machine, plug in the external drive and then load up the document it fails to resolve the bookmark, throws the following error:
Error Domain=NSCocoaErrorDomain Code=259 "The file couldn’t be opened because it isn’t in the correct format."
For completeness here is the code to resolve the bookmark:
do {
let url = try URL(
resolvingBookmarkData: data,
options: Self.bookmarkResolutionOptions,
relativeTo: nil,
bookmarkDataIsStale: &isStale
)
} catch {
print(error)
/// ... error handling code here
}
Do I therefore assume that I cannot achieve this, and will have to ask the user to re-authorise this folder on the second machine?
Hello,
In the documentation for an ARView we see a diagram that shows that all Entity's are connected via AnchorEntity's to the Scene:
https://developer.apple.com/documentation/realitykit/arview
What happens when we are using a RealityView? Here the documentation suggests we direclty add Entity's:
https://developer.apple.com/documentation/realitykit/realityview/
Three questions:
Do we need to add Entitys to an AnchorEntity first and add this via content.add(...)?
Is an Entity ignored by physics engine if attached via an Anchor?
If both the AnchorEntity and an attached Entity is added via content.add(...), does is its anchor's position ignored?
I'm trying to build a Shader in "Reality Composer Pro" that updates from a start time. Initially I tried the following:
The idea was that when the startTime was 0, the output would be 0, but then I would set startTime from within code and this would be compared with the current GPU time, and difference used to drive another part of the shader graph:
if
let testEntity = root.findEntity(named: "Test"),
var shaderGraphMaterial = testEntity.components[ModelComponent.self]?.materials.first as? ShaderGraphMaterial
{
let time = CFAbsoluteTimeGetCurrent()
try! shaderGraphMaterial.setParameter(name: "StartTime", value: .float(Float(time)))
testEntity.components[ModelComponent.self]?.materials[0] = shaderGraphMaterial
}
However, I haven't found a reference to the time the shader would be using.
So now I am trying to write an EntityAction to achieve the same effect. Instead of comparing a start time to the GPU's time I'm trying to animate one of the shader's uniform input. However, I'm not sure how to specify the bind target. Here's my attempt so far:
import RealityKit
struct ShaderAction: EntityAction {
let startValue: Float
let targetValue: Float
var animatedValueType: (any AnimatableData.Type)? { Float.self }
static func registerEntityAction() {
ShaderAction.subscribe(to: .updated) { event in
guard let animationState = event.animationState else { return }
let value = simd_mix(event.action.startValue, event.action.targetValue, Float(animationState.normalizedTime))
animationState.storeAnimatedValue(value)
}
}
}
extension Entity {
func updateShader(from startValue: Float, to targetValue: Float, duration: Double) {
let fadeAction = ShaderAction(startValue: startValue, targetValue: targetValue)
if let shaderAnimation = try? AnimationResource.makeActionAnimation(for: fadeAction, duration: duration, bindTarget: .material(0).customValue) {
playAnimation(shaderAnimation)
}
}
}
'''
Currently when I run this I get an assertion failure: 'Index out of range (operator[]:line 797) index = 260, max = 8'
Furthermore, even if it didn't crash I don't understand how to pass a binding to the custom shader value "startValue".
Any clues of how to achieve this effect - even if it's a completely different way.
Topic:
Graphics & Games
SubTopic:
RealityKit
Tags:
RealityKit
Reality Composer Pro
Shader Graph Editor
Hello,
I'm writing an EntityAction that animates a material base tint between two different colours. However, the colour that is being actually set differs in RGB values from that requested.
For example, trying to set an end target of R0.5, G0.5, B0.5, results in a value of R0.735357, G0.735357, B0.735357. I can also see during the animation cycle that intermediate actual tint values are also incorrect, versus those being set.
My understanding is the the values of material base colour are passed as a SIMD4. Therefore I have a couple of helper extensions to convert a UIColor into this format and mix between two colours. Note however, I don't think the issue is with this functions - even if their outputs are wrong, the final value of the base tint doesn't match the value being set.
I wondered if this was a colour space issue?
import simd
import RealityKit
import UIKit
typealias Float4 = SIMD4<Float>
extension Float4 {
func mixedWith(_ value: Float4, by mix: Float) -> Float4 {
Float4(
simd_mix(x, value.x, mix),
simd_mix(y, value.y, mix),
simd_mix(z, value.z, mix),
simd_mix(w, value.w, mix)
)
}
}
extension UIColor {
var float4: Float4 {
var r: CGFloat = 0.0
var g: CGFloat = 0.0
var b: CGFloat = 0.0
var a: CGFloat = 0.0
getRed(&r, green: &g, blue: &b, alpha: &a)
return Float4(Float(r), Float(g), Float(b), Float(a))
}
}
struct ColourAction: EntityAction {
let startColour: SIMD4<Float>
let targetColour: SIMD4<Float>
var animatedValueType: (any AnimatableData.Type)? { SIMD4<Float>.self }
init(startColour: UIColor, targetColour: UIColor) {
self.startColour = startColour.float4
self.targetColour = targetColour.float4
}
static func registerEntityAction() {
ColourAction.subscribe(to: .updated) { event in
guard let animationState = event.animationState else { return }
let interpolatedColour = event.action.startColour.mixedWith(event.action.targetColour, by: Float(animationState.normalizedTime))
animationState.storeAnimatedValue(interpolatedColour)
}
}
}
extension Entity {
func updateColour(from currentColour: UIColor, to targetColour: UIColor, duration: Double, endAction: @escaping (Entity) -> Void = { _ in }) {
let colourAction = ColourAction(startColour: currentColour, targetColour: targetColour, endedAction: endAction)
if let colourAnimation = try? AnimationResource.makeActionAnimation(for: colourAction, duration: duration, bindTarget: .material(0).baseColorTint) {
playAnimation(colourAnimation)
}
}
}
The EntityAction can only be applied to an entity with a ModelComponent (because of the material), so it can be called like so:
guard
let modelComponent = entity.components[ModelComponent.self],
let material = modelComponent.materials.first as? PhysicallyBasedMaterial else
{
return
}
let currentColour = material.baseColor.tint
let targetColour = UIColor(_colorLiteralRed: 0.5, green: 0.5, blue: 0.5, alpha: 1.0)
entity.updateColour(from:currentColour, to: targetColour, duration: 2)
I have a scene built up in RealityComposerPro, in which I've added a ParticleEmitter with isEmitting set to False and 'Loop' set to True.
In my app, when I toggle isEmitting to True there can be a delay of a few seconds before the ParticleEmitter starts.
However, if I programatically add the emitter in code at that point, it starts immediately.
To be clear, I'm seeing this on the VisionOS simulator - I don't have access to a device at this time.
Am I misunderstanding how to control the ParticleEmitter when I need precise control on when it starts.
Had anyone experienced convexCast causing a crash and what might be behind it?
Here's the call stack:
Prior to MacOS 26, Multiple Pickers could be laid out with a uniform width. For example:
struct LayoutExample: View {
let fruits = ["apple", "banana", "orange", "kiwi"]
let veg = ["carrot", "cauliflower", "peas", "Floccinaucinihilipilification Cucurbitaceae"]
@State private var selectedFruit: String = "kiwi"
@State private var selectedVeg: String = "carrot"
var body: some View {
VStack(alignment: .leading) {
Picker(selection: $selectedFruit) {
ForEach(fruits, id: \.self, content: Text.init)
} label: {
Text("Fruity choice")
.frame(width: 150, alignment: .trailing)
}
.frame(width: 300)
Picker(selection: $selectedVeg) {
ForEach(veg, id: \.self, content: Text.init)
} label: {
Text("Veg")
.frame(width: 150, alignment: .trailing)
}
.frame(width: 300)
}
}
}
Renders like this, prior to MacOS26:
But now looks like this under MacOS 26:
Is there anyway to control the size of the picker selection in MacOS 26?
I have found that following code runs without issue from Xcode, either in Debug or Release mode, yet crashes when running from the binary produced by archiving - i.e. what will be sent to the app store.
import SwiftUI
import AVKit
@main
struct tcApp: App {
var body: some Scene {
WindowGroup {
VideoPlayer(player: nil)
}
}
}
This is the most stripped down code that shows the issue. One can try and point the VideoPlayer at a file and the same issue will occur.
I've attached the crash log:
Crash log
Please note that this was seen with Xcode 26.2 and MacOS 26.2.
I'm unable to compile my project for UnitTests at present - get a load of Cannot Find XXXXX in Scope errors.
Anybody else getting this, or ideas of how to resolve.
I've tried cleaning the build folder, restarting Xcode, checking my unit test code file is only a member of the test target.
Code compiles for the debug and production builds.
I am unable to get VisionOS 2.0 (simulator) to receive the GCControllerDidConnect notification and thus am unable to setup support for a gamepad. However, it works in VisionOS 1.2.
For VisionOS 2.0 I've tried adding:
.handlesGameControllerEvents(matching: .gamepad) attribute to the view
Supports Controller User Interaction to Info.plist
Supported game controller types -> Extended Gamepad to Info.plist
...but the notification still doesn't fire. It does when the code is run from VisionOS 1.2 simulator, both of which have the Send Game Controller To Device option enabled.
Here is the example code. It's based on the Xcode project template. The only files updated were ImmersiveView.swift and Info.plist, as detailed above:
import SwiftUI
import GameController
import RealityKit
import RealityKitContent
struct ImmersiveView: View {
var body: some View {
RealityView { content in
// Add the initial RealityKit content
if let immersiveContentEntity = try? await Entity(named: "Immersive", in: realityKitContentBundle) {
content.add(immersiveContentEntity)
}
NotificationCenter.default.addObserver(
forName: NSNotification.Name.GCControllerDidConnect,
object: nil, queue: nil) { _ in
print("Handling GCControllerDidConnect notification")
}
}
.modify {
if #available(visionOS 2.0, *) {
$0.handlesGameControllerEvents(matching: .gamepad)
} else {
$0
}
}
}
}
extension View {
func modify<T: View>(@ViewBuilder _ modifier: (Self) -> T) -> some View {
return modifier(self)
}
}
Does anyone have experience of creating their own EntityActions?
Say for example I wanted one that faded up the opacity of an entity, then once it had completed set another property on one of the entity's components.
I understand that I could use the FromToByAction to control the opacity (and have this working), but I am interested to learn how to create my own dedicated EntityAction, and finding the documentation hard to fathom.
I got as far as creating a struct conforming to EntityAction protocol:
var animatedValueType: (any AnimatableData.Type)?
}
Subscribing to update events on this:
FadeUpAction.subscribe(to: .updated) { event in
guard let animationState = event.animationState else {
return
}
// My animation state is always nil, so I never get here!
let newValue = \\\Some Calc...
animationState.storeAnimatedValue(newValue)
}
And setting it up as an animation on an entity:
let action = FadeUpAction()
if let animation = try? AnimationResource.makeActionAnimation(
for:action,
duration: 2.0,
bindTarget: .opacity
) {
entity.playAnimation(animation)
}
...but haven't been able to understand how to extract the current timeDelta or set the value in the event handler.
Any pointers?