Post

Replies

Boosts

Views

Activity

Conforming @MainActor class to Codable
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!
1
1
3.2k
Jan ’24
SwiftUI macOS document app architecture in a concurrent world
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) }
1
0
2.3k
Aug ’21
NSFilePresenter update not firing on iPad - does on Mac with identical code.
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!
1
0
1.6k
Mar ’22
What does this TSAN exception indicate?
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.
1
1
1.1k
Aug ’22
Security scoped bookmark and external drives
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: &amp;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?
1
0
1.3k
Nov ’22
RealityView and Anchors
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?
1
0
1.4k
May ’24
Animating a RealityComposerPro shader's uniform input value
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.
1
0
698
Feb ’25
EntityAction for MaterialBaseTint - incorrect colours
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)
1
0
629
Feb ’25
RealityKit particleEmitter delay starting when toggling isEmitting
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.
1
0
586
Feb ’25
SwiftUI Picker layout under MacOS26
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?
1
0
124
Sep ’25
VideoPlayer crashes on Archive build
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.
1
0
541
Dec ’25
How to correctly move a TextField selection cursor when inserting UTF16 text
I'm trying to implement a feature whereby a user can tap a button to insert a character at the cursor in a TextField - the cursor then needs to be moved forward to be in front of the insert character. I'm having trouble with characters such as π which are UTF16 encoded. In the following sample app, enter the following sequence: Enter 9 by keyboard tap + Enter 9 by keyboard tap π Enter 9 via keyboard tap + he TextField will show '9+9π+9' (i.e. the final + is inserted before 9 rather than after it. Any insight into what I am doing wrong? import SwiftUI @main struct TextInsertApp: App { var body: some Scene { WindowGroup { ContentView() } } } struct ContentView: View { @State private var text: String = "" @State private var selection: TextSelection? = nil var body: some View { TextField("", text: $text, selection: $selection) .background(.gray.opacity(0.4)) Button("+") { insert("+") } Button("π") { insert("π") } } func insert(_ insertString: String) { if let selection { if case let .selection(range) = selection.indices { if selection.isInsertion { text.insert(contentsOf: insertString, at: range.lowerBound) } else { text.replaceSubrange(range, with: insertString) } let cursor = text.utf16.index(range.upperBound, offsetBy: insertString.count) self.selection = .init(insertionPoint: cursor) } } else { text += insertString selection = .init(range: text.utf16.endIndex..<text.utf16.endIndex) } } }
1
0
182
Jan ’26
Orphaned XCode simulator disk images
Recently I noticed that although my drive showed ~800Gb of usage, the folders within totally to around ~600Gb (and yes I was including hidden 'dot' files/folders. After some inspection I found that there are a whole set of Disk Media Images, that appear to be related to XCode simulators. Here's an extract from the command line diskutil list command: /dev/disk5 (synthesized): #: TYPE NAME SIZE IDENTIFIER 0: APFS Container Scheme - +17.6 GB disk5 Physical Store disk4s1 1: APFS Volume iOS 26.2 Simulator 17.1 GB disk5s1 /dev/disk6 (disk image): #: TYPE NAME SIZE IDENTIFIER 0: GUID_partition_scheme +14.2 GB disk6 1: Apple_APFS Container disk7 14.2 GB disk6s1 /dev/disk7 (synthesized): #: TYPE NAME SIZE IDENTIFIER 0: APFS Container Scheme - +14.2 GB disk7 Physical Store disk6s1 1: APFS Volume XROS 26.2 Simulator 13.8 GB disk7s1 /dev/disk8 (disk image): #: TYPE NAME SIZE IDENTIFIER 0: GUID_partition_scheme +17.2 GB disk8 1: Apple_APFS Container disk9 17.2 GB disk8s1 /dev/disk9 (synthesized): #: TYPE NAME SIZE IDENTIFIER 0: APFS Container Scheme - +17.2 GB disk9 Physical Store disk8s1 1: APFS Volume iOS 26.0 Simulator 16.7 GB disk9s1 /dev/disk10 (disk image): #: TYPE NAME SIZE IDENTIFIER 0: GUID_partition_scheme +8.5 GB disk10 1: Apple_APFS Container disk11 8.5 GB disk10s1 /dev/disk11 (synthesized): #: TYPE NAME SIZE IDENTIFIER 0: APFS Container Scheme - +8.5 GB disk11 Physical Store disk10s1 1: APFS Volume XROS 2.5 Simulator B... 8.2 GB disk11s1 /dev/disk12 (disk image): #: TYPE NAME SIZE IDENTIFIER 0: GUID_partition_scheme +18.0 GB disk12 1: Apple_APFS Container disk13 18.0 GB disk12s1 /dev/disk13 (synthesized): #: TYPE NAME SIZE IDENTIFIER 0: APFS Container Scheme - +18.0 GB disk13 Physical Store disk12s1 1: APFS Volume XROS 2.5 Simulator 17.5 GB disk13s1 /dev/disk14 (disk image): #: TYPE NAME SIZE IDENTIFIER 0: GUID_partition_scheme +17.6 GB disk14 1: Apple_APFS Container disk15 17.6 GB disk14s1 /dev/disk15 (synthesized): #: TYPE NAME SIZE IDENTIFIER 0: APFS Container Scheme - +17.6 GB disk15 Physical Store disk14s1 1: APFS Volume iOS 26.1 Simulator 17.1 GB disk15s1 /dev/disk16 (disk image): #: TYPE NAME SIZE IDENTIFIER 0: GUID_partition_scheme +14.1 GB disk16 1: Apple_APFS Container disk17 14.1 GB disk16s1 /dev/disk17 (synthesized): #: TYPE NAME SIZE IDENTIFIER 0: APFS Container Scheme - +14.1 GB disk17 Physical Store disk16s1 1: APFS Volume XROS 26.1 Simulator 13.7 GB disk17s1 /dev/disk18 (disk image): #: TYPE NAME SIZE IDENTIFIER 0: GUID_partition_scheme +17.6 GB disk18 1: Apple_APFS Container disk19 17.6 GB disk18s1 /dev/disk19 (synthesized): #: TYPE NAME SIZE IDENTIFIER 0: APFS Container Scheme - +17.6 GB disk19 Physical Store disk18s1 1: APFS Volume iOS 26.1 Simulator 17.1 GB disk19s1 /dev/disk20 (disk image): #: TYPE NAME SIZE IDENTIFIER 0: GUID_partition_scheme +9.1 GB disk20 1: Apple_APFS Container disk21 9.1 GB disk20s1 /dev/disk21 (synthesized): #: TYPE NAME SIZE IDENTIFIER 0: APFS Container Scheme - +9.1 GB disk21 Physical Store disk20s1 1: APFS Volume iOS 18.5 Simulator B... 8.8 GB disk21s1 /dev/disk22 (disk image): #: TYPE NAME SIZE IDENTIFIER 0: GUID_partition_scheme +20.7 GB disk22 1: Apple_APFS Container disk23 20.7 GB disk22s1 /dev/disk23 (synthesized): #: TYPE NAME SIZE IDENTIFIER 0: APFS Container Scheme - +20.7 GB disk23 Physical Store disk22s1 1: APFS Volume iOS 18.5 Simulator 20.2 GB disk23s1 I am unable to unmount them, either from the command line or Disk Utility. How do I go about this?
1
0
71
1w
GCControllerDidConnect notification not received in VisionOS 2.0
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) } }
2
1
968
Dec ’24
Conforming @MainActor class to Codable
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!
Replies
1
Boosts
1
Views
3.2k
Activity
Jan ’24
SwiftUI macOS document app architecture in a concurrent world
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) }
Replies
1
Boosts
0
Views
2.3k
Activity
Aug ’21
NSFilePresenter update not firing on iPad - does on Mac with identical code.
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!
Replies
1
Boosts
0
Views
1.6k
Activity
Mar ’22
What does this TSAN exception indicate?
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.
Replies
1
Boosts
1
Views
1.1k
Activity
Aug ’22
Security scoped bookmark and external drives
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: &amp;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?
Replies
1
Boosts
0
Views
1.3k
Activity
Nov ’22
RealityView and Anchors
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?
Replies
1
Boosts
0
Views
1.4k
Activity
May ’24
Animating a RealityComposerPro shader's uniform input value
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.
Replies
1
Boosts
0
Views
698
Activity
Feb ’25
EntityAction for MaterialBaseTint - incorrect colours
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)
Replies
1
Boosts
0
Views
629
Activity
Feb ’25
RealityKit particleEmitter delay starting when toggling isEmitting
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.
Replies
1
Boosts
0
Views
586
Activity
Feb ’25
RealityKit convexCast causing a crash
Had anyone experienced convexCast causing a crash and what might be behind it? Here's the call stack:
Replies
1
Boosts
0
Views
93
Activity
Jun ’25
SwiftUI Picker layout under MacOS26
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?
Replies
1
Boosts
0
Views
124
Activity
Sep ’25
VideoPlayer crashes on Archive build
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.
Replies
1
Boosts
0
Views
541
Activity
Dec ’25
How to correctly move a TextField selection cursor when inserting UTF16 text
I'm trying to implement a feature whereby a user can tap a button to insert a character at the cursor in a TextField - the cursor then needs to be moved forward to be in front of the insert character. I'm having trouble with characters such as π which are UTF16 encoded. In the following sample app, enter the following sequence: Enter 9 by keyboard tap + Enter 9 by keyboard tap π Enter 9 via keyboard tap + he TextField will show '9+9π+9' (i.e. the final + is inserted before 9 rather than after it. Any insight into what I am doing wrong? import SwiftUI @main struct TextInsertApp: App { var body: some Scene { WindowGroup { ContentView() } } } struct ContentView: View { @State private var text: String = "" @State private var selection: TextSelection? = nil var body: some View { TextField("", text: $text, selection: $selection) .background(.gray.opacity(0.4)) Button("+") { insert("+") } Button("π") { insert("π") } } func insert(_ insertString: String) { if let selection { if case let .selection(range) = selection.indices { if selection.isInsertion { text.insert(contentsOf: insertString, at: range.lowerBound) } else { text.replaceSubrange(range, with: insertString) } let cursor = text.utf16.index(range.upperBound, offsetBy: insertString.count) self.selection = .init(insertionPoint: cursor) } } else { text += insertString selection = .init(range: text.utf16.endIndex..<text.utf16.endIndex) } } }
Replies
1
Boosts
0
Views
182
Activity
Jan ’26
Orphaned XCode simulator disk images
Recently I noticed that although my drive showed ~800Gb of usage, the folders within totally to around ~600Gb (and yes I was including hidden 'dot' files/folders. After some inspection I found that there are a whole set of Disk Media Images, that appear to be related to XCode simulators. Here's an extract from the command line diskutil list command: /dev/disk5 (synthesized): #: TYPE NAME SIZE IDENTIFIER 0: APFS Container Scheme - +17.6 GB disk5 Physical Store disk4s1 1: APFS Volume iOS 26.2 Simulator 17.1 GB disk5s1 /dev/disk6 (disk image): #: TYPE NAME SIZE IDENTIFIER 0: GUID_partition_scheme +14.2 GB disk6 1: Apple_APFS Container disk7 14.2 GB disk6s1 /dev/disk7 (synthesized): #: TYPE NAME SIZE IDENTIFIER 0: APFS Container Scheme - +14.2 GB disk7 Physical Store disk6s1 1: APFS Volume XROS 26.2 Simulator 13.8 GB disk7s1 /dev/disk8 (disk image): #: TYPE NAME SIZE IDENTIFIER 0: GUID_partition_scheme +17.2 GB disk8 1: Apple_APFS Container disk9 17.2 GB disk8s1 /dev/disk9 (synthesized): #: TYPE NAME SIZE IDENTIFIER 0: APFS Container Scheme - +17.2 GB disk9 Physical Store disk8s1 1: APFS Volume iOS 26.0 Simulator 16.7 GB disk9s1 /dev/disk10 (disk image): #: TYPE NAME SIZE IDENTIFIER 0: GUID_partition_scheme +8.5 GB disk10 1: Apple_APFS Container disk11 8.5 GB disk10s1 /dev/disk11 (synthesized): #: TYPE NAME SIZE IDENTIFIER 0: APFS Container Scheme - +8.5 GB disk11 Physical Store disk10s1 1: APFS Volume XROS 2.5 Simulator B... 8.2 GB disk11s1 /dev/disk12 (disk image): #: TYPE NAME SIZE IDENTIFIER 0: GUID_partition_scheme +18.0 GB disk12 1: Apple_APFS Container disk13 18.0 GB disk12s1 /dev/disk13 (synthesized): #: TYPE NAME SIZE IDENTIFIER 0: APFS Container Scheme - +18.0 GB disk13 Physical Store disk12s1 1: APFS Volume XROS 2.5 Simulator 17.5 GB disk13s1 /dev/disk14 (disk image): #: TYPE NAME SIZE IDENTIFIER 0: GUID_partition_scheme +17.6 GB disk14 1: Apple_APFS Container disk15 17.6 GB disk14s1 /dev/disk15 (synthesized): #: TYPE NAME SIZE IDENTIFIER 0: APFS Container Scheme - +17.6 GB disk15 Physical Store disk14s1 1: APFS Volume iOS 26.1 Simulator 17.1 GB disk15s1 /dev/disk16 (disk image): #: TYPE NAME SIZE IDENTIFIER 0: GUID_partition_scheme +14.1 GB disk16 1: Apple_APFS Container disk17 14.1 GB disk16s1 /dev/disk17 (synthesized): #: TYPE NAME SIZE IDENTIFIER 0: APFS Container Scheme - +14.1 GB disk17 Physical Store disk16s1 1: APFS Volume XROS 26.1 Simulator 13.7 GB disk17s1 /dev/disk18 (disk image): #: TYPE NAME SIZE IDENTIFIER 0: GUID_partition_scheme +17.6 GB disk18 1: Apple_APFS Container disk19 17.6 GB disk18s1 /dev/disk19 (synthesized): #: TYPE NAME SIZE IDENTIFIER 0: APFS Container Scheme - +17.6 GB disk19 Physical Store disk18s1 1: APFS Volume iOS 26.1 Simulator 17.1 GB disk19s1 /dev/disk20 (disk image): #: TYPE NAME SIZE IDENTIFIER 0: GUID_partition_scheme +9.1 GB disk20 1: Apple_APFS Container disk21 9.1 GB disk20s1 /dev/disk21 (synthesized): #: TYPE NAME SIZE IDENTIFIER 0: APFS Container Scheme - +9.1 GB disk21 Physical Store disk20s1 1: APFS Volume iOS 18.5 Simulator B... 8.8 GB disk21s1 /dev/disk22 (disk image): #: TYPE NAME SIZE IDENTIFIER 0: GUID_partition_scheme +20.7 GB disk22 1: Apple_APFS Container disk23 20.7 GB disk22s1 /dev/disk23 (synthesized): #: TYPE NAME SIZE IDENTIFIER 0: APFS Container Scheme - +20.7 GB disk23 Physical Store disk22s1 1: APFS Volume iOS 18.5 Simulator 20.2 GB disk23s1 I am unable to unmount them, either from the command line or Disk Utility. How do I go about this?
Replies
1
Boosts
0
Views
71
Activity
1w
GCControllerDidConnect notification not received in VisionOS 2.0
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) } }
Replies
2
Boosts
1
Views
968
Activity
Dec ’24