Swift is a powerful and intuitive programming language for Apple platforms and beyond.

Posts under Swift tag

200 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

ManipulationComponent Not Translating using indirect input
When using the new RealityKit Manipulation Component on Entities, indirect input will never translate the entity - no matter what settings are applied. Direct manipulation works as expected for both translation and rotation. Is this intended behaviour? This is different from how indirect manipulation works on Model3D. How else can we get translation from this component? visionOS 26 Beta 2 Build from macOS 26 Beta 2 and Xcode 26 Beta 2 Attached is replicable sample code, I have tried this in other projects with the same results. var body: some View { RealityView { content in // Add the initial RealityKit content if let immersiveContentEntity = try? await Entity(named: "MovieFilmReel", in: reelRCPBundle) { ManipulationComponent.configureEntity(immersiveContentEntity, allowedInputTypes: .all, collisionShapes: [ShapeResource.generateBox(width: 0.2, height: 0.2, depth: 0.2)]) immersiveContentEntity.position.y = 1 immersiveContentEntity.position.z = -0.5 var mc = ManipulationComponent() mc.releaseBehavior = .stay immersiveContentEntity.components.set(mc) content.add(immersiveContentEntity) } } }
3
2
101
3w
Creating RTP-MIDI Sessions via MIDINetworkSession C API (dlopen/dlsym) on macOS 15?
I’m an amateur developer working on a free utility for composers/producers, for which the macOS release needs to create and name RTP-MIDI sessions in Audio MIDI Setup from the command line (so I can ship a small C helper instead of telling users to click through the UI). Here’s what I’ve tried so far, without luck: • Plist hacks: Injecting entries into ~/Library/Audio/MIDI Configurations/*.mcfg works when AMS is closed, but AMS immediately locks and reverts my changes when it’s open. • CoreMIDI C API: I can create virtual ports with MIDISourceCreate, but attempting MIDIObjectGetDataProperty on the apple.midirtp.session plugin always returns err –10836. • Obj-C & Swift: Loading MIDINetworkSession and calling defaultSession, init, setNetworkName: and setting enabled = YES doesn’t produce a new session object in the Network panel. • dlopen/dlsym: I extracted the real CoreMIDI binary out of the dyld shared cache and tried binding _MIDINetworkSessionCreate, _SetName, _SetEnabled, etc., but all the symbols come back null or my tool segfaults. • Plugin registration: I’ve pulled the factory UUID (70C9C5EA-7C65-11D8-B317-000393A34B5A) from /System/Library/Extensions/AppleMIDIRTPDriver.plugin/Contents/Info.plist and called CFPlugInRegisterFactories, but it still never exposes the session-creation calls. At this point I’m convinced I’m either loading the wrong binary or missing one critical step in registering the RTP-MIDI plugin’s private API. Can anyone point me to: The exact path of the dylib or bundle that actually exports the MIDINetworkSessionCreate/MIDINetworkSessionSetName/MIDINetworkSessionSetEnabled symbols? A minimal working snippet (C or Obj-C) that reliably creates and names a Network-MIDI session? Any pointers, sample code, or even ideas about where Apple hides this functionality on macOS 15 would be hugely appreciated. Thanks!
0
1
64
Jun ’25
Circular Reference Error in Xcode 26
I have my project running perfectly fine on Xcode 16. However, in Xcode 26 it doesn't build due to an error that I do not understand. I have three files that pertain to this error: // FriendListResponse.swift import Foundation struct FriendListResponse: Decodable { var friendships: [Friendship] var collections: [FriendCollection] } // Friendship.swift import Foundation struct Friendship: Decodable { var createdAt: String var friendId: Int var friendUserId: Int // user ID of the friend var friendUsername: String var id: Int var tagNames: [String] } // FriendCollection.swift struct FriendCollection: Decodable { var id: Int var permalink: String var tagNames: [String] var title: String } On the first file, FriendListResponse.swift, I am the simple error message "circular reference." I do not understand how these self-contained structs could create a circular reference. Although I have other data types in my project, none of them are even referenced in these files except for Friendship and FriendCollection. The FriendListResponse is a struct that is created from JSON values that are fetched from an API. This is the function that fetches the JSON: public static func listFriends(username: String) async throws -> [Friendship] { let data = try await sendGETRequest( url: "people/\(username)/friends/list.json" ) print(String(data: data, encoding: .utf8)!) let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase let wrapper = try decoder.decode(FriendListResponse.self, from: data) return wrapper.friendships } // Note: the function sendGETRequest is just // a function that I have created that takes a set // of parameters and returns a data object // using the HTTP GET protocol. I don't think // that it is related to this issue. However, if you // think that it is, I can share the code for that. This error has also happened in a few other cases within contained networks of my data structure. I do not know why this error is only appearing once I launch Xcode 26 beta with my project files. I would think that this error also would appear in Xcode 16.4. Any help would be greatly appreciated in my process to compile my project on Xcode 26!
7
0
286
Jun ’25
JSONDecoder enum-keyed dictionary bug
Hello everyone, I think I've discovered a bug in JSONDecoder and I'd like to get a quick sanity-check on this, as well as hopefully some ideas to work around the issue. When attempting to decode a Decodable struct from JSON using JSONDecoder, the decoder throws an error when it encounters a dictionary that is keyed by an enum and somehow seems to think that the enum is an Array<Any>. Here's a minimal reproducible example: let jsonString = """ { "variations": { "plural": "tests", "singular": "test" } } """ struct Json: Codable { let variations: [VariationKind: String] } enum VariationKind: String, Codable, Hashable { case plural = "plural" case singular = "singular" } and then the actual decoding: let json = try JSONDecoder().decode( Json.self, from: jsonString.data(using: .utf8)! ) print(json) The expected result would of course be the following: Json( variations: [ VariationKind.plural: "tests", VariationKind.singular: "test" ] ) But the actual result is an error: Swift.DecodingError.typeMismatch( Swift.Array<Any>, Swift.DecodingError.Context( codingPath: [ CodingKeys(stringValue: "variations", intValue: nil) ], debugDescription: "Expected to decode Array<Any> but found a dictionary instead.", underlyingError: nil ) ) So basically, the JSONDecoder tries to decode Swift.Array<Any> but encounters a dictionary (duh), and I have no idea why this is happening. There are literally no arrays anywhere, neither in the actual JSON string, nor in any of the Codable structs. Curiously, if I change the dictionary from [VariationKind: String] to [String: String], everything works perfectly. So something about the enum seems to cause confusion in JSONDecoder. I've tried to fix this by implementing Decodable myself for VariationKind and using a singleValueContainer, but that causes exactly the same error. Am I crazy, or is that a bug?
1
0
70
Jun ’25
Extracting IP with swift on visionOS
Hey everyone, I’m developing an app for visionOS where I need to display the Apple Vision Pro’s current IP address. For this I’m using the following code, which works for iOS, macOS, and visionOS in the simulator. Only on a real Apple Vision Pro it’s unable to extract an IP. Could it be that visionOS currently doesn’t allow this? Have any of you had the same experience and found a workaround? var address: String = "no ip" var ifaddr: UnsafeMutablePointer<ifaddrs>? = nil if getifaddrs(&ifaddr) == 0 { var ptr = ifaddr while ptr != nil { defer { ptr = ptr?.pointee.ifa_next } let interface = ptr?.pointee let addrFamily = interface?.ifa_addr.pointee.sa_family if addrFamily == UInt8(AF_INET) { if let name: Optional<String> = String(cString: (interface?.ifa_name)!), name == "en0" { var hostname = [CChar](repeating: 0, count: Int(NI_MAXHOST)) getnameinfo(interface?.ifa_addr, socklen_t((interface?.ifa_addr.pointee.sa_len)!), &hostname, socklen_t(hostname.count), nil, socklen_t(0), NI_NUMERICHOST) address = String(cString: hostname) } } } freeifaddrs(ifaddr) } return address } Thanks in advance for any insights or tips! Best Regards, David
2
1
105
Jun ’25
macOS UIApplication not in scope
I'm trying to disable the sleep timer when a button is pressed in my macOS app but the problem is that from the resources I've seen elsewhere the code doesn't work. The code I'm trying is UIApplication.shared.isIdleTimerDisabled = true When I try and run my app I get this error Cannot find 'UIApplication' in scope From what I've managed to search for regarding this it appears that UIApplication might be an iOS thing, but how can I adapt this for macOS? I've found some code samples from 5+ years ago but it involves lots of code. Surely, in 2025 macOS can disable sleep mode as easy as iOS, right? How can I achieve this please?
Topic: UI Frameworks SubTopic: General Tags:
1
0
70
Jun ’25
How can you communicate that a .xcframework is a dependency OF the swift package inside Swift package definition?
I am sort of trying to do the opposite of what others are doing. I have a target called CopyFramework that creates a CopyFramework.framework within my main xcproj file. I set up this target because a specific framework (we can call it Tools.xcframework) is distributed as a binary. That framework file lives within the code. Tools.xcframework is structured like so Tools.xcframework (Coding/testBuild/DynamicToolFrameworks/Tools.xcframework) info.plist ios-arm64/ Tools.xcframework/ Tools (executable file) Tools.bundle Headers/ Info.plist Modules/ Tools.swiftmodule/ arm64-apple-ios.abi.json arm64-apple-ios.private.swiftinterface arm64-apple-ios.swiftdoc arm64-apple-ios.swiftinterface module.modulemap module.private.modulemap PrivateHeaders/ ios-arm64_x86_64-simulator/ When the CopyFramework target is run xcode does a few steps which copy the correct version of this framework to derived data. Process Tools.xcframework (iOS) Coding/testBuild/DynamicToolFrameworks/Tools.xcframework /Library/Developer/Xcode/DerivedData/testBuild-sha/Build/Products/Debug-iphoneos/Tools.framework ios cd /Users/calebkierum/Coding/testBuild builtin-process-xcframework --xcframework Coding/testBuild/DynamicToolFrameworks/Tools.xcframework --platform ios --target-path Library/Developer/Xcode/DerivedData/testBuild-sha/Build/Products/Debug-iphoneos Meaning essentially that the Tools.xcframework for the proper platform is taken from Tools.xcframework/ios-arm64 and copied to Library/Developer/Xcode/DerivedData/testBuild-sha/Build/Products/Debug-iphoneos/Tools.xcframework I am writing a Swift Package that needs to be able to reference the correct Tools.xcframework. I have set it up like so: let package = Package( name: "CoreObjC", platforms: [.iOS(.v17), .macCatalyst(.v17)], products: [ .library(name: "CoreObjC", targets: ["CoreObjC"]), ], dependencies: [ // Does something to here ??? //.package(path: "../testBuild") ], targets: [ .target( name: "CoreObjC", dependencies: [ // Here I would like to be referencing the CopyFramework.framework target within my buildTest.xcproj file .product(name: "CopyFramework", package: /*??? its not in a swift package its a part of an xcproj file*/) ], path: "CoreObjC", publicHeadersPath: "Headers", linkerSettings: [ .linkedFramework("Tools", .when(platforms: [.iOS])), .linkedLibrary("c++") ] ), ], cxxLanguageStandard: CXXLanguageStandard.gnucxx14 ) Now obviously this does not work. I do not know how to communicate to the Package.swift file that the binary dependency is a framework target within my xcproj file. If I do run the target CopyFramework followed by building CoreObjC it works though (so long as you comment out the bits trying to reference CopyFramework). Running the CopyFramework target processes the Tools.xcframework and copies the proper xcframework sub folder to Derived data and the Swift Package build system seems to be able to see it. Is there a way I can get rid of this manual step? Make it so that when I build the CoreObjC target (swift package) that either CopyFramework is run or some other process is run to get the proper xcframework out of Coding/testBuild/DynamicToolFrameworks/Tools.xcframework and into DerivedData? Is it even theoretically possible to have a Swift Package reference a target in a normal xcproj file?
0
0
63
Jun ’25
Module not found when using inheritance
PLATFORM AND VERSION Development environment: Xcode 16.4 (16F6), macOS 15.5 (24F74) Run-time configuration: iOS 18.3.1 DESCRIPTION OF PROBLEM I cannot build my app due to a module not found error when I'm importing Sample-Swift.h header to an ObjectiveC file. I need to use Swift code to ObjectiveC file with Swift code using an external XCFramework. It seems to be related to a mix with ObjectiveC and Swift code when Swift code uses class inheritance from FZWorkoutKit class. With a full Swift project, no issue. STEPS TO REPRODUCE Project https://fizzup.s3.amazonaws.com/files/public/Sample-WK.zip Open the provided project and try to build it. The issue occurs. In MyObject.m file, if you comment the first import (Sample-Swift.h), no issue occurs but I cannot use my Swift code (MyFile class). Uncomment the line commented in step 1. Go to MyFile.swift and change class inheritance from GoModeController (from FZWorkoutKit framework) to UIView (from UIKit). No issue occurs.
0
0
64
Jun ’25
Error querying optional Codable with SwiftData
I'm building a SwiftUI app using SwiftData. In my app I have a Customer model with an optional codable structure Contact. Below is a simplified version of my model: @Model class Customer { var name: String = "" var contact: Contact? init(name: String, contact: Contact? = nil) { self.name = name self.contact = contact } struct Contact: Codable, Equatable { var phone: String var email: String var allowSMS: Bool } } I'm trying to query all the Customers that have a contact with @Query. For example: @Query(filter: #Predicate<Customer> { customer in customer.contact != nil }) var customers: [Customer] However no matter how I set the predicate I always get an error: BugDemo crashed due to an uncaught exception NSInvalidArgumentException. Reason: keypath contact not found in entity Customer. How can I fix this so that I'm able to filter by contact not nil in my Model?
2
0
188
Jun ’25
Is there anywhere to get precompiled WhisperKit models for Swift?
If try to dynamically load WhipserKit's models, as in below, the download never occurs. No error or anything. And at the same time I can still get to the huggingface.co hosting site without any headaches, so it's not a blocking issue. let config = WhisperKitConfig( model: "openai_whisper-large-v3", modelRepo: "argmaxinc/whisperkit-coreml" ) So I have to default to the tiny model as seen below. I have tried so many ways, using ChatGPT and others, to build the models on my Mac, but too many failures, because I have never dealt with builds like that before. Are there any hosting sites that have the models (small, medium, large) already built where I can download them and just bundle them into my project? Wasted quite a large amount of time trying to get this done. import Foundation import WhisperKit @MainActor class WhisperLoader: ObservableObject { var pipe: WhisperKit? init() { Task { await self.initializeWhisper() } } private func initializeWhisper() async { do { Logging.shared.logLevel = .debug Logging.shared.loggingCallback = { message in print("[WhisperKit] \(message)") } let pipe = try await WhisperKit() // defaults to "tiny" self.pipe = pipe print("initialized. Model state: \(pipe.modelState)") guard let audioURL = Bundle.main.url(forResource: "44pf", withExtension: "wav") else { fatalError("not in bundle") } let result = try await pipe.transcribe(audioPath: audioURL.path) print("result: \(result)") } catch { print("Error: \(error)") } } }
0
0
67
Jun ’25
Detect when app window is being moved
Is there a way to detect when your apps (or any app I guess) is being moved by the user clicking and dragging the main window around the desktop at all? I'm trying to find out if there's a way I can find out if a window is being clicked and dragged and whether there's certain triggers to the movement a little bit like shaking an iPhone with Shake to Undo. Thanks
0
0
42
Jun ’25
NavigationStack wrong behaviour in iOS 18.3
Hi, Anybody knows will this occurs when using navigationStack at iOS 18.3? The navigationStack not stay at safeareas the code as simple as that: NavigationStack(path: $navManager.path) { VStack { Text("Hello") } .navigationDestination(for: Route.self) { route in switch route { .... } } } .environmentObject(navManager) .environment(logic)
0
0
90
Jun ’25
Unable to send/receive IPv6 Mutlicast packets on NWConnectionGroup using Apple NF
Hello Everyone, I am currently using macOS 15.5 and XCode 16.4. I am using the following code to send/receive multicast packets on multicast group ff02::1 and port 49153 using Apple NF's NWConnectionGroup. import Network import Foundation // Creating a mutlicast group endpoint let multicastIPv6GroupEndpoint: NWEndpoint = NWEndpoint.hostPort(host: NWEndpoint.Host.ipv6(IPv6Address("ff02::1")!), port: NWEndpoint.Port("49153")!) do { let multicastGroupDescriptor: NWMulticastGroup = try NWMulticastGroup (for: [multicastIPv6GroupEndpoint]) let multicastConnectionGroupDescriptor = NWConnectionGroup (with: multicastGroupDescriptor, using: .udp) multicastConnectionGroupDescriptor.stateUpdateHandler = { state in print ("🕰️ Connection Group state: \(state)") if state == .ready { multicastConnectionGroupDescriptor.send (content: "👋🏻 Hello from the Mac 💻".data (using: .utf8)) { err in print ("➡️ Now, I am trying to send some messages.") if let err = err { print ("💥 Error sending multicast message: \(err)") } else { print ("🌚 Initial multicast message sent") } } } } multicastConnectionGroupDescriptor.setReceiveHandler { message, content, isComplete in if let content = content, let messageString = String (data: content, encoding: .utf8) { print ("⬅️ Received message: \(messageString)") } } multicastConnectionGroupDescriptor.start (queue: .global()) } catch { print ("💥 Error while creating Multicast Group: \(error)") } RunLoop.main.run() I am able to successfully create a NWConnectionGroup without any warnings/errors. The issue occurs when the stateUpdateHandler's callback gets invoked. It first gives me this warning: nw_listener_socket_inbox_create_socket IPV6_LEAVE_GROUP ff02::1.49153 failed [49: Can't assign requested address But then it shows me that the state is ready: 🕰️ Connection Group state: ready After this, when the send is performed, it gives me a bunch of errros: nw_endpoint_flow_failed_with_error [C1 ff02::1.49153 waiting parent-flow (unsatisfied (Local network prohibited), interface: en0[802.11], ipv4, ipv6, uses wifi)] already failing, returning nw_socket_connect [C1:1] connectx(7, [srcif=0, srcaddr=::.62838, dstaddr=ff02::1.49153], SAE_ASSOCID_ANY, 0, NULL, 0, NULL, SAE_CONNID_ANY) failed: [48: Address already in use] nw_socket_connect [C1:1] connectx failed (fd 7) [48: Address already in use] nw_socket_connect connectx failed [48: Address already in use] nw_endpoint_flow_failed_with_error [C1 ff02::1.49153 in_progress socket-flow (satisfied (Path is satisfied), interface: en0[802.11], ipv4, ipv6, dns, uses wifi)] already failing, returning There is no other background process running on the same port. I tried using different ports as well as multicast groups but the same error persists. The same code works fine for an IPv4 multicast group. I have following questions: Why am I getting these errors specifically for IPv6 multicast group but not for IPv4 multicast group? Are there any configurations that needed to be done in order to get this working?
8
0
135
Jun ’25
SwiftMacros Not able to access of main project XCTest File.
I have developed a Swift macro called @CodableInit in the SwiftCodableMacro module, and I’m able to use it successfully in my main project. Here’s an example usage: import SwiftCodableMacro @CodableInit // This is for Codable macros public class ErrorMonitoringWebPlugin { public var identifier: UUID = UUID() // MARK: - Codable required public init(from decoder:Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) identifier = try values.decode(UUID.self, forKey: .identifier) } } However, when I try to write a unit test for the ErrorMonitoringWebPlugin class, I encounter an issue. Here's the test case: func testCodableSubjectIdentifierShouldEqualDecodedSubjectIdentifier() { self.measure { let encoder = JSONEncoder() let data = try? encoder.encode(subject) //Here I am getting this error Class 'JSONEncoder' requires that 'ErrorMonitoringWebPlugin' conform to 'Encodable' let decoder = JSONDecoder() let decodedSubject = try? decoder.decode(ErrorMonitoringWebPlugin.self, from: data!) XCTAssertEqual(subject.identifier, decodedSubject?.identifier) } } The compiler throws an error saying: Class 'JSONEncoder' requires that 'ErrorMonitoringWebPlugin' conform to 'Encodable' Even though the @CodableInit macro is supposed to generate conformance, it seems that this macro-generated code is not visible or active inside the test target. How can I ensure that the @CodableInit macro (from SwiftCodableMacro) is correctly applied and recognized within the XCTest target of my main project?
0
0
44
Jun ’25
Contact UISearchBar missing.
Feedback id: FB16140301 Below are the steps to reproduce the bug in Contacts app. Open Contacts app. Now search for a contact and didSelect that contact. Now slightly hold swipe right(from view's center leading position) as to pop the view but not fully swipe, now release the finger and you can see the back nav bar button missing and tapping the back button position also doesn't perform dismiss action. Now do fully swipe from left to right to dismiss(pop) current view. Here you can see the search bar missing.-> That's the bug.
0
1
61
Jun ’25
Snapshot error
Hey everyone, I have a problem with an app im creating. The code doesn't have any errors but the console has this that pops up: Snapshot request 0x1054191d0 complete with error: <NSError: 0x10541a970; domain: FBSSceneSnapshotErrorDomain; code: 4; "an unrelated condition or state was not satisfied"> { NSLocalizedDescription = an error occurred during a scene snapshotting operation; }
1
0
78
Jun ’25
How to detect if an iPad is configured as a Shared iPad (Apple School Manager)?
I'm working on an iOS/iPadOS app and need to determine programmatically whether the device is a Shared iPad as configured through Apple School Manager (ASM). Shared iPads allow multiple users to sign in with Managed Apple IDs and are typically used in educational environments. I want to identify this configuration at runtime within my app. I’ve looked into UIDevice, NSProcessInfo, and MDM-related APIs but haven't found a reliable way to detect whether the current device is a Shared iPad. Is there an API or method to check if the current iPad is configured as a Shared iPad (via ASM)? Any guidance or code examples would be appreciated.
0
0
31
Jun ’25
@Observable with generic typed throw breaks SwiftCompile
@Observable seems not to work well with generic typed throw. The following code using @Observable with non-generic typed throw builds good: @Observable class ThrowsLoadingViewModel<R, E: Error> { private(set) var isLoading = true private(set) var error: E? = nil private(set) var data: R? = nil private var task: () throws(Error) -> R init(task: @escaping () throws(E) -> R) { self.task = task } func load() { do throws(Error) { self.data = try task() } catch { // self.error = error } self.isLoading = false } } But if I change Line 7 and 14 to generic, it'll breaks the build with a "Command SwiftCompile failed with a nonzero exit code" message : @Observable class ThrowsLoadingViewModel<R, E: Error> { private(set) var isLoading = true private(set) var error: E? = nil private(set) var data: R? = nil private var task: () throws(E) -> R init(task: @escaping () throws(E) -> R) { self.task = task } func load() { do throws(E) { self.data = try task() } catch { // self.error = error } self.isLoading = false } } A the same time, if I remove @Observable, the generic typed throw works again: class ThrowsLoadingViewModel<R, E: Error> { private(set) var isLoading = true private(set) var error: E? = nil private(set) var data: R? = nil private var task: () throws(E) -> R init(task: @escaping () throws(E) -> R) { self.task = task } func load() { do throws(E) { self.data = try task() } catch { // self.error = error } self.isLoading = false } } Currently the possible solution seems to fall back to use ObservableObject...
0
0
28
Jun ’25