Post

Replies

Boosts

Views

Activity

GlobalActor directive doesn't guarantee a function will be called on that actor?
Assuming I have defined a global actor: @globalActor actor MyActor { static let shared = MyActor() } And I have a class, in which a couple of methods need to act under this: class MyClass { @MyActor func doSomething(undoManager: UndoManager) { // Do something here undoManager?.registerUndo(withTarget: self) { $0.reverseSomething(undoManager: UndoManager) } } @MyActor func reverseSomething(undoManager: UndoManager) { // Do the reverse of something here print(\(Thread.isMainThread) /// Prints true when called from undo stack undoManager?.registerUndo(withTarget: self) { $0.doSomething(undoManager: UndoManager) } } } Assume the code gets called from a SwiftUI view: struct MyView: View { @Environment(\.undoManager) private var undoManager: UndoManager? let myObject: MyClass var body: some View { Button("Do something") { myObject.doSomething(undoManager: undoManager) } } } Note that when the action is undone the 'reversing' func it is called on the MainThread. Is the correct way to prevent this to wrap the undo action in a task? As in: @MyActor func reverseSomething(undoManager: UndoManager) { // Do the reverse of something here print(\(Thread.isMainThread) /// Prints true undoManager?.registerUndo(withTarget: self) { Task { $0.doSomething(undoManager: UndoManager) } } }
0
0
1k
Jul ’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: &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
Passing locale into a RegexBuilder as a parameter
I am building a tokeniser, and would like to hold this as a struct, passing in a locale during initiation. Here's the gist of what I would want to write: struct Tokeniser { private let locale: Locale private let integerRegex: Regex init(locale: Locale) { self.locale: Locale self.integerRegex = Regex { Capture { .localizedInteger(locale: locale) } transform: { Token.number($0) } } } func parse(text: String) -> Token { if let match = try integerRegex.firstMatch(in: text) { //... other code here } } \\...other code here } As Regex is generic the compiler suggests to set the integerRegex's type to Regex<Any>, but this triggers another set of compiler issues that I have not been able to figure out what the type should be. So then I tried to write something like this (inspired by SwiftUI): var integerRegex: some Regex { Capture { .localizedInteger(locale: locale) } transform: { Token.number($0) } } But again, the compiler prompts me to enter Regex. The only way I have to be able to get the struct to compiler is to create lazy variables, which then have the side effect that I have to mark my functions as mutable, which have downstream issues when they are called from with SwiftUI structs. lazy var integerRegex = Regex { Capture { .localizedInteger(locale: locale) } } mutating func parse(text: String) -> Token { if let match = try integerRegex.firstMatch(in: text) { } } How can I code this?
0
0
520
Oct ’23
Updating metadata properties of a DNG (or other) format image
Hi, I'm looking to update the metadata properties of a DNG image stored on disc, saving to a new file. Using ImageIO's CGImageSource and CGImageDestination classes, I run into a problem where by the destination doesn't support the type of the source. For example: let imageSourceOptions = [kCGImageSourceShouldCache: false] as CFDictionary if let cgImageSource = CGImageSourceCreateWithURL(sourceURL as CFURL, imageSourceOptions), let type = CGImageSourceGetType(cgImageSource) { guard let imageDestination = CGImageDestinationCreateWithURL(destinationURL as CFURL, type, 1, nil) else { fatalError("Unable to create image destination") } // Code to update properties and write out to destination url } } When this code is executed I get the following errors on the command line when trying to create the destination: 2024-06-30 11:52:25.531530+0100 ABC[7564:273101] [ABC] findWriterForTypeAndAlternateType:119: *** ERROR: unsupported output file format 'com.adobe.raw-image' 2024-06-30 11:52:25.531661+0100 ABC[7564:273101] [ABC] CGImageDestinationCreateWithURL:4429: *** ERROR: CGImageDestinationCreateWithURL: failed to create 'CGImageDestinationRef' I don't see a way to create a destination directly from a source? Yes, the code works for say a JPEG file but I want it to work for any image format that CGImageSource can work with?
0
0
754
Jun ’24
Creating and applying a shader to change an entity's rendering in RealityKit
Hello, I am looking to create a shader to update an entity's rendering. As a basic example say I want to recolour an entity, but leave its original textures showing through: I understand with VisionOS I need to use Reality Composer Pro to create the shader, but I'm lost as how to reference the original colour that I'm trying to update in the node graph. All my attempts appear to completely override the textures in the entity (and its sub-entities) that I want to impact. Also the tutorials / examples I've looked at appear to create materials, not add an effect on top of existing materials. Any hints or pointers? Assuming this is possible, I've been trying to load the material in code, and apply to an entity. But do I need to do this to all child entities, or just the topmost? do { let entity = MyAssets.createModelEntity(.plane) // Loads from bundle and performs config let material = try await ShaderGraphMaterial(named: "/Root/TestMaterial", from: "Test", in: realityKitContentBundle) entity.applyToChildren { $0.components[ModelComponent.self]?.materials = [material] } root.addChild(entity) } catch { fatalError(error.localizedDescription) }
3
0
942
Oct ’24
Custom EntityAction - different behaviour VisionOS 2.6 vs 26
I implemented an EntityAction to change the baseColor tint - and had it working on VisionOS 2.x. import RealityKit import UIKit typealias Float4 = SIMD4<Float> extension UIColor { var float4: Float4 { if cgColor.numberOfComponents == 4, let c = cgColor.components { Float4(Float(c[0]), Float(c[1]), Float(c[2]), Float(c[3])) } else { Float4() } } } struct ColourAction: EntityAction { // MARK: - PUBLIC PROPERTIES let startColour: Float4 let targetColour: Float4 // MARK: - PUBLIC COMPUTED PROPERTIES var animatedValueType: (any AnimatableData.Type)? { Float4.self } // MARK: - INITIATION init(startColour: UIColor, targetColour: UIColor) { self.startColour = startColour.float4 self.targetColour = targetColour.float4 } // MARK: - PUBLIC STATIC FUNCTIONS @MainActor 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 { // MARK: - PUBLIC FUNCTIONS func changeColourTo(_ targetColour: UIColor, duration: Double) { guard let modelComponent = components[ModelComponent.self], let material = modelComponent.materials.first as? PhysicallyBasedMaterial else { return } let colourAction = ColourAction(startColour: material.baseColor.tint, targetColour: targetColour) if let colourAnimation = try? AnimationResource.makeActionAnimation(for: colourAction, duration: duration, bindTarget: .material(0).baseColorTint) { playAnimation(colourAnimation) } } } This doesn't work in VisionOS 26. My current fix is to directly set the material base colour - but this feels like the wrong approach: @MainActor static func registerEntityAction() { ColourAction.subscribe(to: .updated) { event in guard let animationState = event.animationState, let entity = event.targetEntity, let modelComponent = entity.components[ModelComponent.self], var material = modelComponent.materials.first as? PhysicallyBasedMaterial else { return } let interpolatedColour = event.action.startColour.mixedWith(event.action.targetColour, by: Float(animationState.normalizedTime)) material.baseColor.tint = UIColor(interpolatedColour) entity.components[ModelComponent.self]?.materials[0] = material animationState.storeAnimatedValue(interpolatedColour) } } So before I raise this as a bug, was I doing anything wrong in the former version and got lucky? Is there a better approach?
0
0
122
Sep ’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
89
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
413
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
164
3w