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

Invalid Swift Support
Hi, Can someone please help me with the below issue, I validated the app before distributing from Xcode, and it passed. but I received a mail from Apple Developer Relations saying there a problem, but I don't have any clue how to solve this problem. ITMS-90429: Invalid Swift Support - The files libswiftDarwin.dylib, libswiftDispatch.dylib, libswiftCoreGraphics.dylib, libswiftCoreFoundation.dylib, libswiftUIKit.dylib, libswiftMetal.dylib, libswiftCore.dylib, libswiftFoundation.dylib, libswiftQuartzCore.dylib, libswiftos.dylib, libswiftObjectiveC.dylib, libswiftCoreImage.dylib aren’t at the expected location /Payload/connectdots.app/Frameworks. Move the file to the expected location, rebuild your app using the current public (GM) version of Xcode, and resubmit it. I dont know where these dylibs are now and how to move them. Also I am using Xcode 15.3. what does it mean current public version of Xcode Thanks in Advance, Thirupathi.
0
0
34
15h
Most efficient way to call a function upon variable state change
Hi, I have a button view that is used in many different ways in an app that I'm working on. One of the ways it is used is in an account creation form. Since the button is in a child view, the action: { } button function isn't available in the view where the input field variables are. I could import the class with the function to the button view but I don't want to pass the input field variables into the button view. I tried binding a boolean variable to the button view and checked for it's state change in the parent view using .onChange(), but the use case for that I found was depreciated and I'm unable to revert the state of the variable in the .onChange function. To reiterate, in a main view, I need to call a function in a given class and pass variables to it, upon a button being pressed in a child view. Any help would be greatly appreciated.
1
0
82
14h
WidgetKit Not running in iOS 14/15 (FBSOpenApplicationServiceErrorDomain)
I was adding WidgetExtension target for my old project. The widget target is running fine in iOS 17, In my case, widget need to support iOS 14 and above, so I updated my widget code to old style, To removing WidgetConfigurationIntent and AppIntentTimelineProvider. import WidgetKit import SwiftUI struct Provider: TimelineProvider { func placeholder(in context: Context) -> SimpleEntry { SimpleEntry() } func getSnapshot(in context: Context, completion: @escaping (SimpleEntry) -> Void) { completion(SimpleEntry()) } func getTimeline(in context: Context, completion: @escaping (Timeline<SimpleEntry>) -> Void) { completion(Timeline(entries: [SimpleEntry()], policy: .never)) } typealias Entry = SimpleEntry } struct SimpleEntry: TimelineEntry { let date: Date = Date() } struct NCWidgetEntryView : View { var entry: Provider.Entry var body: some View { VStack { Text("Time:") Text(entry.date, style: .time) } } } struct NCWidget: Widget { let kind: String = "NCWidget" var body: some WidgetConfiguration { StaticConfiguration(kind: kind, provider: Provider()) { entry in NCWidgetEntryView(entry: entry) } .configurationDisplayName("DisplayName") .description("description") } } In my case, the code was working fine in iOS 17 simulator, But if I try to run in iOS 15, it returns the below error code-SendProcessControlEvent:toPid: encountered an error: Error Domain=com.apple.dt.deviceprocesscontrolservice Code=8 "Failed to show Widget 'com.name-pprd.NCWidgetExtension' error: Error Domain=FBSOpenApplicationServiceErrorDomain Code=5 "The request to open "com.apple.springboard" failed." UserInfo={NSLocalizedDescription=The request to open "com.apple.springboard" failed., NSLocalizedFailureReason=Unexpected error type., NSUnderlyingError=0x600003570b40 {Error Domain=BSServiceConnectionErrorDomain Code=3 "XPC error received on message reply handler" UserInfo={BSErrorCodeDescription=OperationFailed, NSLocalizedFailureReason=XPC error received on message reply handler}}, BSErrorCodeDescription=InvalidResponse}." UserInfo={NSLocalizedDescription=Failed to show Widget 'com.name-pprd.NCWidgetExtension' error: Error Domain=FBSOpenApplicationServiceErrorDomain Code=5 "The request to open "com.apple.springboard" failed." UserInfo={NSLocalizedDescription=The request to open "com.apple.springboard" failed., NSLocalizedFailureReason=Unexpected error type., NSUnderlyingError=0x600003570b40 {Error Domain=BSServiceConnectionErrorDomain Code=3 "XPC error received on message reply handler" UserInfo={BSErrorCodeDescription=OperationFailed, NSLocalizedFailureReason=XPC error received on message reply handler}}, BSErrorCodeDescription=InvalidResponse}., NSUnderlyingError=0x600003570bd0 {Error Domain=FBSOpenApplicationServiceErrorDomain Code=5 "The request to open "com.apple.springboard" failed." UserInfo={NSLocalizedDescription=The request to open "com.apple.springboard" failed., NSLocalizedFailureReason=Unexpected error type., NSUnderlyingError=0x600003570b40 {Error Domain=BSServiceConnectionErrorDomain Code=3 "XPC error received on message reply handler" UserInfo={BSErrorCodeDescription=OperationFailed, NSLocalizedFailureReason=XPC error received on message reply handler}}, BSErrorCodeDescription=InvalidResponse}}} Domain: DTXMessage Code: 1 User Info: { DVTErrorCreationDateKey = "2024-07-20 17:30:58 +0000"; } -- System Information macOS Version 14.5 (Build 23F79) Xcode 15.0.1 (22266) (Build 15A507) Timestamp: 2024-07-20T23:00:58+05:30 In widget target Minimum target is 14.0 In App target Minimum target is 13.0
1
0
103
1d
Weird crashes when accessing Swift Array
For some time now Xcode has been downloading crash reports from users of my app about crashes related to arrays. One of them looks like this: ... Code Type: ARM-64 Parent Process: launchd [1] User ID: 501 Date/Time: 2024-07-18 14:59:40.4375 +0800 OS Version: macOS 15.0 (24A5289h) ... Crashed Thread: 0 Exception Type: EXC_BREAKPOINT (SIGTRAP) Exception Codes: 0x0000000000000001, 0x00000001045048b8 Termination Reason: Namespace SIGNAL, Code 5 Trace/BPT trap: 5 Terminating Process: exc handler [1771] Thread 0 Crashed: 0 MyApp 0x00000001045048b8 specialized Collection.map<A>(_:) + 596 1 MyApp 0x00000001045011e4 MyViewController.validateToolbarButtons() + 648 (MyViewController.swift:742) ... The relevant code looks like this: class MyViewController { func validateToolbarButtons() { let indexes = tableView.clickedRow == -1 || tableView.selectedRowIndexes.contains(tableView.clickedRow) ? tableView.selectedRowIndexes : IndexSet(integer: tableView.clickedRow) let items = indexes.map({ myArray[$0] }) ... } } The second crash looks like this: ... Code Type: X86-64 (Native) Parent Process: launchd [1] User ID: 502 Date/Time: 2024-07-15 15:53:35.2229 -0400 OS Version: macOS 15.0 (24A5289h) ... Crashed Thread: 0 Exception Type: EXC_BAD_INSTRUCTION (SIGILL) Exception Codes: 0x0000000000000001, 0x0000000000000000 Termination Reason: Namespace SIGNAL, Code 4 Illegal instruction: 4 Terminating Process: exc handler [13244] Thread 0 Crashed: 0 libswiftCore.dylib 0x00007ff812904fc0 _assertionFailure(_:_:flags:) + 288 1 MyApp 0x0000000101a31e04 specialized _ArrayBuffer._getElementSlowPath(_:) + 516 2 MyApp 0x00000001019d04eb MyObject.myProperty.setter + 203 (MyObject.swift:706) 3 MyApp 0x000000010192f66e MyViewController.controlTextDidChange(_:) + 190 (MyViewController.swift:166) ... And the relevant code looks like this: class MyObject { var myProperty: [MyObject] { get { ... } set { let items = newValue.map({ $0.id }) ... } } } What could cause such crashes? Could they be caused by anything other than concurrent access from multiple threads (which I'm quite sure is not the case here, as I only access these arrays from the main thread)?
0
0
79
1d
SwiftUI URLRequest Warning: "Connection has no local endpoint"
I have a simple SwiftUI application that sends a URLRequest as shown in the code snippet below: import SwiftUI @main struct GOGODemoApp: App { var body: some Scene { WindowGroup { MyView() } } } struct MyView: View { var body: some View { Button("Click") { sendHTTPRequest(to: "https://www.google.com") { code, err in print("Finished, code: \(code ?? -1), err: \(String(describing: err))") } } } } func sendHTTPRequest(to urlString: String, completion: @escaping (Int?, Error?) -> Void) { guard let url = URL(string: urlString) else { completion(nil, NSError(domain: "InvalidURL", code: 0, userInfo: nil)) return } let task = URLSession.shared.dataTask(with: url) { _, resp, error in if let httpResponse = resp as? HTTPURLResponse { completion(httpResponse.statusCode, error) } else { completion(-1, error) } } task.resume() } However, Xcode prints the following warning messages: nw_connection_copy_connected_local_endpoint_block_invoke [C1] Connection has no local endpoint nw_connection_copy_connected_local_endpoint_block_invoke [C1] Connection has no local endpoint nw_connection_copy_connected_local_endpoint_block_invoke [C3] Connection has no local endpoint nw_connection_copy_connected_local_endpoint_block_invoke [C3] Connection has no local endpoint Finished, code: 200, err: nil What does the warning 'Connection has no local endpoint' mean? Thank you for your assistance!
0
0
65
1d
How do I do unit tests for code using system objects?
That's probably a bad title, let's try with specifics: we have a network extension, it has some classes / functions of its own, and they, when push comes to build, depend on (for example) NEAppProxyFlow and its subclasses. The code is written in Swift, since it is the language of the future. If I want to do a unit test for my code, I need to provide something that at least looks like NEAppProxyFlow, since I can't otherwise create one. I thought I could provide my own NetworkExtension module for test case, but that... did not work well, and I still don't understand why. On the other hand, I'm really bad at making unit tests, so the odds that I'm missing something fairly obvious to most other people are pretty high.
2
0
65
1d
Siri not recognizing the parameter in the phrase
I am trying to create an "OpenShowIntent" that allows the user to open a show from outside the app by either invoking the shortcut and provide a showName and/or by asking Siri "Open (.$showName) in (.applicationName)". Currently the shortcut works and but Siri doesn't recognize the showName and keeps on loading when I say the phrase with a show name. I was wondering where I am going wrong. Here are some of the code below: OpenShowIntent.swift: import Foundation import AppIntents import Models @available(iOS 16.0, *) struct OpenShowIntent: AppIntent { static var title: LocalizedStringResource = "Open a Show" static var openAppWhenRun = true @Parameter(title: "Show", optionsProvider: ShowEntityQuery()) var show: ShowEntity? @Parameter(title: "Show Name") var showName: String static var parameterSummary: some ParameterSummary { Summary("Open \(\.$showName) in (APP NAME)") } @MainActor func perform() async throws -> some IntentResult & ProvidesDialog { var showToOpen: ShowEntity if let show = show { showToOpen = show } else { let params = ElasticSearchParams(query: showName) let searchResults = try await IntentsHelper.getShows(searchParams: params) let entities = searchResults.map { show in ShowEntity(id: show.id, name: show.displayName, posterUrl: show.posterImageUrl) } showToOpen = try await $show.requestDisambiguation( among: entities, dialog: "Choose a show from this list?" ) } let deepLink = DeepLink( type: .show( showId: showToOpen.id, showDateStr: nil, voucher: nil, reviewModalParams: nil ) ) let url = try deepLink.createURL(source: nil) IntentsHelper.openLink(url: url) return .result(dialog: "Show '\(showToOpen.name)' opened successfully.") } } ShowEntity.swift: import Foundation import AppIntents import Models @available(iOS 16.0, *) struct ShowEntity: AppEntity { typealias DefaultQuery = ShowEntityQuery var id: Int var name: String var posterUrl: URL? static var typeDisplayRepresentation: TypeDisplayRepresentation = "Show" var displayRepresentation: DisplayRepresentation { var image: DisplayRepresentation.Image? if let imageUrl = posterUrl { image = DisplayRepresentation.Image(url: imageUrl) } return DisplayRepresentation( title: LocalizedStringResource(stringLiteral: name), subtitle: nil, image: image ) } static var defaultQuery = ShowEntityQuery() init(id: Int, name: String, posterUrl: URL?) { self.id = id self.name = name self.posterUrl = posterUrl } } ShowEntityQuery.swift: import Foundation import AppIntents import Models @available(iOS 16.0, *) struct ShowEntityQuery: EntityStringQuery { func entities(for identifiers: [Int]) async throws -> [ShowEntity] { let params = ElasticSearchParams(showIds: identifiers) let searchResult = try await IntentsHelper.getShows(searchParams: params) return searchResult.map { show in ShowEntity(id: show.id, name: show.displayName, posterUrl: show.posterImageUrl) } } func suggestedEntities() async throws -> [ShowEntity] { let params = ElasticSearchParams( showIds: BookmarksManager.sharedManager.getBookmarkShowIdsAsArray() ) let searchResult = try await IntentsHelper.getShows(searchParams: params) return searchResult.map { show in ShowEntity(id: show.id, name: show.displayName, posterUrl: show.posterImageUrl) } } func entities(matching query: String) async throws -> [ShowEntity] { let params = ElasticSearchParams(query: query) print("entities(matching:) called with query: \(query)") let searchResult = try await IntentsHelper.getShows(searchParams: params) return searchResult.map { show in ShowEntity(id: show.id, name: show.displayName, posterUrl: show.posterImageUrl) } } } ShortcutsProvider.swift: import Foundation import AppIntents @available(iOS 16.0, *) struct TTShortcuts: AppShortcutsProvider { static var appShortcuts: [AppShortcut] { return [ AppShortcut( intent: OpenShowIntent(), phrases: [ "View show in \(.applicationName)", "Open \(\.$showName) in \(.applicationName)", "Show \(\.$showName) in \(.applicationName)", "Find \(\.$showName) in \(.applicationName)", "Search for \(\.$showName) in \(.applicationName)" ], shortTitle: "Open show", systemImageName: "pencil.circle" ) ] } static var shortcutTileColor: ShortcutTileColor = .blue }
0
0
108
3d
SwiftUI List misaligned with title bar.
Hello! I am making an app in SwiftUI and find it hard to make good-looking UIs with SwiftUI when using the List. When having a big navigation bar, the list appears misaligned with the title. This is a preview within Xcode. Don't know if that changes anything 🤷. Below is the code. I should note I am using Xcode 16 beta 3. // // SwiftUIView.swift // import SwiftUI struct SwiftUIView: View { struct D { var id: Int var name: String var identifier: String } let items: [(Int, D)] = [ (0, D(id: 0, name: "Test One", identifier: "one.example.test")), (1, D(id: 1, name: "Test One", identifier: "two.example.test")), (2, D(id: 2, name: "Test One", identifier: "three.example.test")), (3, D(id: 3, name: "Test One", identifier: "four.example.test")) ] var body: some View { NavigationStack { List(items, id: \.1.id) { idx, d in VStack(alignment: .leading) { Text(d.name) .bold() Text(d.identifier) } } .navigationTitle("Hello Title") } } } #Preview { SwiftUIView() }
2
0
118
3d
How to safely create root and branch objects in a custom zone?
I encountered issues with some branch objects being assigned to multiple zones error (on iOS 17.5.1 and above). I get the errors when calling persistentContainer.shareshare(:to:completion:) and persistentContainer.persistUpdatedShare(:in:completion:). "The operation couldn't be completed. Request '89D3F62D-548D-4816-9F1B-594390BD8F70' was aborted because the mirroring delegate never successfully initialized due to error: Error Domain=NSCocoaErrorDomain Code=134060 "A Core Data error occurred." UserInfo={NSLocalizedFailureReason=Object graph corruption detected. Objects related to 'Oxa2255fdc1fa980c5 x-coredata://CB800FA2-6054-4D91-8EBC-E9E31890344F/CDChildObject/p588' are assigned to multiple zones: {l <CKRecordZonelD: 0x3026a1170; zoneName=com.apple.coredata.cloud-kit.share.5D30F204-5970-489F- BC2E-F863F1808A93, ownerName=defaultOwner>, <CKRecordZonelD: 0x302687b40; zoneName=com.apple.coredata.cloud-kit.zone, ownerName=_defaultOwner>" In my setup, I moved all my root objects into one custom zone (there is only one custom zone in my private database). In one of my root object, there are 6 'one-to-one' and 2 'one-to-many' relationships. The branch objects can contains other relationships. Create root object flow: func saveToPersistent(_ object: ViewModelObject) { serialQueue.async { let context = backgroundContext() context.performAndWait { // Create new baby with its one-to-one child objects. let cdNewBaby = self.newCDBaby(object, context) if let share = self.getShareZone(.privateStore).first { self.moveToShareZone(pObjects, share: share, store: .privateStore) } CoreDataManager.single.saveContext(context) self.updateZoneNSaveContext([cdNewBaby], context: context) } // context.perform } // serialQueue.async } func backgroundContext() -> NSManagedObjectContext { let context = persistentContainer.newBackgroundContext() context.transactionAuthor = contextAuthor context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy return context } func getShareZone(_ storeType: StoreType, zoneName: String? = nil) -> [CKShare] { var shares: [CKShare] = [] do { shares = try persistentContainer.fetchShares(in: stores[storeType]) } catch { print(error) return shares } if let zoneName = zoneName { shares = shares({ $0.recordID.zoneID.zoneName == zoneName }) } return shares } func moveToShareZone(_ sharedObjects: [NSManagedObject], share: CKShare, store: StoreType) { self.persistentContainer.share(sharedObjects, to: share) { managedObjects, share, container, error in if let error = error { print(error) } else if let share = share, let store = self.stores[store] { self.persistentContainer.persistUpdatedShare(share, in: store) { (share, error) in if let error = error { print(error) } } } } } // moveToShareZone Create one-to-many relationship branch object flow: serialQueue.async { let context = self.backgroundContext() context.performAndWait { // MARK: Retrieve the Root record let pObjects = CDRootRecord.fetchRecord(rootRecord.uuidString, store: store, zoneName: zoneName, context: context) if let pRootRecord = pObjects.first { self.newCDLogContent(pRootRecord.self, viewModelObject: viewModelObject, context: context) // MARK: Save Log CoreDataManager.single.saveContext(context) } } // context.performAndWait } // serialQueue Questions: (1) Should I save a root object first before share to custom zone; or share to custom zone first before save? (I implemented save before share to zone in the past and found some issues on iOS16 where the object is not saved; and end of sharing object before save which works) (2) As I understand, if a branch record is saved under a root record, it should automatically go into the root record. Or do I have to also share the branch record to the custom zone?
1
0
69
3d
Print Center on iPad: Issues Persist After Canceling and Resending Print Jobs.
Environment→ ・Device: iPad 9th generation ・OS:**iOS17.5.1 ・Printer model:EPSON PX-S730 Current issues→ 01). After canceling a print job in the Print Center, the Print Center screen on the iPad does not close. 02). When the printer is turned on and a new print job is sent, the Print Center shows the ongoing waiting job instead of proceeding with printing. Problem Description→ The AirPrint feature on an iPad 9th generation running iOS 17.5.1 is being used with an EPSON PX-S730 printer. When sending a print job while the printer is off, the Print Center shows the ongoing printing job. If the print job is canceled in the Print Center, the Print Center screen on the iPad does not close. After turning on the printer and sending the print job again, the Print Center shows the ongoing waiting job. What I want→ The Print Center screen on the iPad to close automatically after canceling a print job. Test code: Note: printController.print response is completed but Print Center status is waiting let printInfo = UIPrintInfo(dictionary: nil) printInfo.jobName = "Print Job" printController.printInfo = printInfo let pdfURL = Bundle.main.url(forResource: "sample", withExtension: "pdf")! printController.printingItem = pdfURL let printer = UIPrinter(url: printerUrl) printController.print(to: printer, completionHandler: { [self] printController, completed, error in if(error != nil){ print("error"). }else if completed{ print("completed") //this scenario handles completion response }else{ print("cancel") } })
0
0
72
3d
Printer Offline: No Error Message Received for Print Job Submission
Environment→ ・Device: iPad 9th generation ・OS:**iOS17.5.1 ・Printer model:EPSON PX-S730 Current issues→ An error message is not returned from the printer if a print job is sent while the printer is off. Problem Description→ The AirPrint feature on an iPad 9th generation running iOS 17.5.1 is being used with an EPSON PX-S730 printer. When sending a print job while the printer is off, the Print Center shows the ongoing printing job, but the printing cannot be executed because the printer is off. What I want→ I would like an error to be returned when I submit a printing job while the printer is off. Test code: Note: printController.print response is completed but Print Center status is printing let printInfo = UIPrintInfo(dictionary: nil) printInfo.jobName = "Print Job" printController.printInfo = printInfo let pdfURL = Bundle.main.url(forResource: "sample", withExtension: "pdf")! printController.printingItem = pdfURL let printer = UIPrinter(url: printerUrl) printController.print(to: printer, completionHandler: { [self] printController, completed, error in if(error != nil){ print("error"). }else if completed{ print("completed"). //this scenario handles completion response }else{ print("cancel") } })
0
0
63
3d
Using MLHandActionClassifierwith visionOS
How do I use either of these data sources with MLHandActionClassifierwith on visionOS? MLHandActionClassifier.DataSource.labeledKeypointsDataFrame MLHandActionClassifier.DataSource.labeledKeypointsData visionOS ARKit HandTracking provides us with 27 joints and 3D co-ordinates which differs from the 21 joint, 2D co-ordinates that these two data sources mention in their documentation.
0
0
88
4d
How Does Update Closure Work in RealityView
I have looked here: Reality View Documentation Found this thread: RealityView Update Closure Thread I am not able to find documentation on how the update closure works. I am loading attachments using reality view's attachment feature (really helpful). I want to remove them programmatically from another file. I found that @State variables can be used. But I am not able to modify them from out side of the ImmersiveView swift file. The second problem I faced was even if I update them inside the file. My debugging statements don't execute. So exactly when does update function run. I know it get's executed at the start (twice for some reason). It also get's executed when I add a window using: openWindow?(id: "ButtonView") I need to use the update closure because I am also not able to get the reference to RealityViewAttachment outside the RealityView struct. My Code(only shown the code necessary. there is other code): @State private var pleaseRefresh = "" @StateObject var model = HandTrackingViewModel() var body: some View { RealityView { content, attachments in if let immersiveContentEntity = try? await Entity(named: "Immersive", in: realityKitContentBundle) { content.add(immersiveContentEntity) } content.add(model.setupContentEntity()) content.add(entityDummy) print("View Loaded") } update: { content, attachments in print("Update Closure Executed") if (model.editWindowAdded) { print("WINDOW ADDED") let theattachment = attachments.entity(for: "sample")! entityDummy.addChild(theattachment) // more code here } } attachments: { Attachment(id: "sample") { Button(action: { model.canEditPos = true model.canRotate = false pleaseRefresh = "changed" }) { HStack { Image(systemName: "pencil.and.outline") .resizable() .scaledToFit() .frame(width: 32, height: 32) Text("Edit Placement") .font(.caption) } .padding(4) } .frame(width: 160, height: 60) } } How can the update method (or the code inside it) run when I want it to? I am new to swift. I apologize if my question seems naive.
1
0
136
4d
Xcode not recognizing GoogleMaps theme colors with Swift
I have an Xcode project written in Objc where Xcode recognizes GoogleMaps code (GMS SDK 9) and applies appropriate theme colors. I'm porting the app into Swift and Xcode does not seem recognize GMS code for theme colors. The theme otherwise works and the Swift/GMS code works (ie the app works). I've tried 'Clean All Targets', deleting the DerivedData folder, cleaning the Xcode cache, re-installing the GMS SDK (both CocoaPod & manual methods) etc. When the Swift project is re-opened, Xcode shows the project is being re-indexed. After indexing, the rest of the code is 'colorized' - but not the GMS code. Both StackOverflow & StackExchange rejected this question. And Apple Developer Support has not been able to help (Case ID: 102334926141). Any advice will be greatly appreciated. TIA
6
0
122
2d
Model Container Sendable Throwing Error in Swift 6
Hi all, I just wanted to ask how people were using ModelActor with the Swift 6 language mode enabled. My current implementation involves passing the ModelContainer to my ModelActor, which worked in Sonoma and previous betas of Sequoia, however in the current Beta 3, I get this error: "Sending 'self.modelContext.container' risks causing data races" I am a bit confused by this, as from what I understand, ModelContainer conforms to Sendable, so ideally this error should not be thrown. Is this a bug in Beta 3? Thanks in advance.
1
1
166
5d
Attach a Attachment to the hand VisionOS
I am trying to attach a button to user's left hand. the position is tracked. the button stays above the user's left hand. but it doesn't face the user. or it doesn't even face where the wrist is pointing. this is the main code snippet: if (model.editWindowAdded) { let originalMatrix = model.originFromWristLeft let theattachment = attachments.entity(for: "sample")! entityDummy.addChild(theattachment) let testrotvalue = simd_quatf(real: 0.9906431, imag: SIMD3<Float>(-0.028681312, entityDummy.orientation.imag.y, 0.025926698)) entityDummy.orientation = testrotvalue theattachment.position = [0, 0.1, 0] var timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) {_ in let originalMatrix = model.originFromWristLeft print(originalMatrix.columns.0.y) let testrotvalue = simd_quatf(real: 0.9906431, imag: SIMD3<Float>(-0.028681312,0.1, 0.025926698)) entityDummy.orientation = testrotvalue } }
2
0
153
5d
Non-Optional One-To-Many Relationship Missing Object In Array
I'm encountering an issue with a one-to-many relationship between two models using SwiftData. Here's a simple example of my models: @Model final class TVSeries { var title: String @Relationship(deleteRule: .cascade, inverse: \Episode.tvSeries) var episodes: [Episode] init(title: String, episodes: [Episode] = []) { self.title = title self.episodes = episodes } } @Model final class Episode { var title: String var tvSeries: TVSeries // <- Works fine when optional init(title: String, tvSeries: TVSeries) { self.title = title self.tvSeries = tvSeries } } After creating and saving a TVSeries instance with an associated Episode, fetching the TVSeries instance shows that the episodes array remains empty whereas the back-link to the TVSeries works as expected. Here's the relevant test case: struct SwiftDataTestingTests { @Test func testFullInit() async throws { // Configure SwiftData context let config = ModelConfiguration(isStoredInMemoryOnly: true) let container = try ModelContainer(for: TVSeries.self, Episode.self, configurations: config) let context = ModelContext(container) context.autosaveEnabled = false // Create entries let tvSeries = TVSeries(title: "New Series") let episode = Episode(title: "Episode 1", tvSeries: tvSeries) context.insert(episode) try context.save() // Fetch tv series let tvSeriesDescriptor = FetchDescriptor<TVSeries>() let tvSeriesResult = try context.fetch(tvSeriesDescriptor) #expect(tvSeriesResult.count == 1) let fetchedTVSeries = try #require(tvSeriesResult.first) #expect(fetchedTVSeries.episodes.count == 1) // <- Expectation failed: (fetchedTVSeries.episodes.count → 0) == 1 // Fetch episodes let episodeDescriptor = FetchDescriptor<Episode>() let episodeResult = try context.fetch(episodeDescriptor) #expect(episodeResult.count == 1) let fetchedEpisode = try #require(episodeResult.first) #expect(fetchedEpisode.tvSeries.title == "New Series") } } Everything seems fine when I make the tvSeries attribute in the Episode model optional, but I would prefer to leave it explicit. I tested this on the latest XCode and XCode Beta versions running macOS Sonoma XCode Version: 15.4 (15F31d) XCode Beta Version: 16.0 beta 3 (16A5202i) MacOS Version: 14.5 (23F79) Any insights or suggestions on what might be causing this issue would be greatly appreciated. Thank you!
0
0
102
6d