Post

Replies

Boosts

Views

Activity

Importing Data into SwiftData in the Background Using ModelActor and @Query
I have an app with fairly typical requirements - I need to insert some data (in my case from the network but could be anything) and I want to do it in the background to keep the UI responsive. I'm using SwiftData. I've created a ModelActor that does the importing and using the debugger I can confirm that the data is indeed being inserted. On the UI side, I'm using @Query and a SwiftUI List to display the data but what I am seeing is that @Query is not updating as the data is being inserted. I have to quit and re-launch the app in order for the data to appear, almost like the context running the UI isn't communicating with the context in the ModelActor. I've included a barebones sample project. To reproduce the issue, tap the 'Background Insert' button. You'll see logs that show items being inserted but the UI is not showing any data. I've tested on the just released iOS 18b3 seed (22A5307f). The sample project is here: https://hanchor.s3.amazonaws.com/misc/SwiftDataBackgroundV2.zip
23
13
5.7k
Aug ’25
Saving SwiftData in Background Does Not Update @Query
I'm trying to use SwiftData for a new app after ~20 years of Core Data (and EOF before that). So while I'm new to SwiftData, I'm not new to Apple persistence frameworks. I've got a pretty typical workflow - need to load some JSON from the network, convert that into model objects. I've created an actor using the @ModelActor macro and I'm using that to do the network fetch and insert. I can set breakpoints in this code and see that it does indeed run and it's running on a non-main queue. That all seems fine. The problem is that my @Query powered variable in my SwiftUI user interface does not get updated when this data is loaded and saved as I would expect it to. I'm passing in the container to the actor using modelContext.container from the same modelContext that is powering the view / in the environment. My understanding was that like Core Data before it, the SwiftData framework was listening for the relevant notifications passed by the container/context, processing those and updating the UI but I can only see my data if I quit and relaunch the app. This seems like it should be a very common use case but I've not found much online. Not sure if that means I'm just doing something fundamentally wrong or what. Tested on both iOS 18 and 17 with the same results. Anyone else doing this successfully? What could I be doing wrong?
1
6
1.3k
Jul ’24
CloudKit.js: Querying for IN of Array of References
Howdy,Let's say I've got an 'Order' record type and a 'Transaction' record type. Transaction has a reference to order.I have an array of recordNames of orders and I want to get transactions that match any of the orders. Can I do this? I've been having trouble. var orderReferences = []; orderIdentifiers.forEach(function(orderIdentifier) { var orderReference = { recordName: orderIdentifier, action: "NONE" }; orderReferences.push(orderReference); }); var query = { recordType: "Transaction", filterBy: [{ fieldName: 'order', comparator: 'IN', fieldValue: { value: orderReferences } }] };(forgive my perhaps terrible JS - it's not a language I use a lot)This doesn't work, I get an error back from the server saying it could not decode my reference (I assume because I'm trying to query with an array of references?)How is this supposed to work?Thanks!
3
0
1.7k
Jan ’21
Trying (failing) to use CreateML to create model for named entity rec w/ Natural Language framework
I'm trying to use CreateML to build a model I can use with the new Natural Language framework for domain-specific named entity recognition in scanning some text. It's actually very very similar to the example in the WWDC '18 video introducing the Natural Language Framework where they add a bunch of products and recognize them.The problem I'm having is that the results I'm getting when I run text through an NLTagger with this model are very inaccurate.Imagine an app for people visiting Las Vegas, NV. I want to be able to identify names of hotels, restaurants and other activities as such. I have training data that looks like this (there's a lot more but it all follows this pattern).{"tokens":["Bellagio","Buffet at Bellagio","Fix Restaurant and Bar","Harvest","Jasmine","Lago","Le Cirque","Michael Mina","Noodles","Picasso","Prime","Spago","Yellowtail","Spa \u0026 Salon","Fountains of Bellagio","Gallery of Fine Art","Hyde Lounge","Lily Bar and Lounge","O ","Petrossian Bar"],"labels":["Hotel","Restaurant","Restaurant","Restaurant","Restaurant","Restaurant","Restaurant","Restaurant","Restaurant","Restaurant","Restaurant","Restaurant","Restaurant","Activity","Activity","Activity","Activity","Activity","Activity","Activity"]}Here's a Playground with my test code. With the below, I'd expect 'Bellagio' to come back as 'Hotel' but when I print the tokens and tags, they all come back as... not that. And some times, the same token comes back as two different tags (i.e. 'MGM Grand' below).What am I doing wrong? Bad training data? Bad training data format? Unrealistic expectations? I have no idea what I'm doing?The last one is definitely true.In the WWDC video demo, it seems to work great and it seems very similar to what I'm doing so not sure where I'm off.import CreateML import Foundation import NaturalLanguage let wordFilePath = Bundle.main.path(forResource:"vegas_words", ofType: "json")! let wordFileURL = URL(fileURLWithPath: wordFilePath) let trainingData = try MLDataTable(contentsOf: wordFileURL) let model = try MLWordTagger(trainingData: trainingData, tokenColumn: "tokens", labelColumn: "labels") let compiledModel = try NLModel(mlModel: model.model) let text = "When in Las Vegas I like to stay at the luxury hotel Bellagio or perhaps Wynn Las Vegas but not MGM Grand or the Luxor. Sometimes I like to dine at Delmonico at The Venetian or at one of the places at MGM Grand." let range = text.startIndex..<text.endIndex var vegasTagScheme = NLTagScheme("Vegas") var tagger = NLTagger(tagSchemes: [.nameType, vegasTagScheme]) tagger.string = text tagger.setModels([compiledModel], forTagScheme: vegasTagScheme) tagger.setLanguage(NLLanguage("en"), range: range) tagger.enumerateTags(in: range, unit: .word, scheme: vegasTagScheme, options: [.omitWhitespace, .joinNames, .omitPunctuation]) { (tag, tokenRange) -> Bool in let token = text[tokenRange] if let tag = tag { print("\(token): \(tag.rawValue)") } return true }When: Hotel in: Hotel Las Vegas: Hotel I: Restaurant like: Restaurant to: Restaurant stay: Restaurant at: Restaurant the: Restaurant luxury: Restaurant hotel: Restaurant Bellagio: Restaurant or: Restaurant perhaps: Restaurant Wynn Las Vegas: Restaurant but: Restaurant not: Restaurant MGM Grand: Restaurant or: Restaurant the: Restaurant Luxor: Restaurant Sometimes: Activity I: Activity like: Activity to: Activity dine: Activity at: Activity Delmonico: Activity at: Activity The: Activity Venetian: Activity or: Activity at: Activity one: Activity of: Activity the: Activity places: Activity at: Activity MGM Grand: Activity
3
0
2k
Mar ’21
Shortcuts: "There was a problem with the app"
I'm playing with Shortcuts.Siri is telling me "There was a problem with the app" whenever I call the completion handler with a success message. My failure states work.I backed out my custom code and literally just returning static strings in my completion and I'm still getting the error. I'm not really sure how to debug this or where it's going wrong... I'm sending a correctly formed intent response.??
11
0
9.4k
Jun ’21
Model Guardrails Too Restrictive?
I'm experimenting with using the Foundation Models framework to do news summarization in an RSS app but I'm finding that a lot of articles are getting kicked back with a vague message about guardrails. This seems really common with political news but we're talking mainstream stuff, i.e. Politico, etc. If the models are this restrictive, this will be tough to use. Is this intended? FB17904424
9
4
626
Nov ’25
UILabel truncates inside UIStackView?
So, using UIStackView, I've noticed that some UILabels seem to want to truncate instead of wrap to a new line... Anyone else noticed this? The label's number of lines is set to 0.There's a stack view with two labels in it. The stack view is setup to be horizontally and vertically centered in its superview with at least 10 points from the trailing and leading margins. I'd expect the labels to wrap to a new line, not truncate.Any thoughts?
6
2
22k
Jan ’23
Swift Data Predicate Evaluation Crashes in Release Build When Generics Used
I'm using Swift Data for an app that requires iOS 18. All of my models conform to a protocol that guarantees they have a 'serverID' String variable. I wrote a function that would allow me to pass in a serverID String and have it fetch the model object that matched. Because I am lazy and don't like writing the same functions over and over, I used a Self reference so that all of my conforming models get this static function. Imagine my model is called "WhatsNew". Here's some code defining the protocol and the fetching function. protocol RemotelyFetchable: PersistentModel { var serverID: String { get } } extension WhatsNew: RemotelyFetchable {} extension RemotelyFetchable { static func fetchOne(withServerID identifier: String, inContext modelContext: ModelContext) -> Self? { var fetchDescriptor = FetchDescriptor<Self>() fetchDescriptor.predicate = #Predicate<Self> { $0.serverID == identifier } do { let allModels = try modelContext.fetch(fetchDescriptor) return allModels.first } catch { return nil } } } Worked great! Or so I thought... I built this and happily ran a debug build in the Simulator and on devices for months while developing the initial version but when I went to go do a release build for TestFlight, that build reliably crashed on every device with a message like this: SwiftData/DataUtilities.swift:65: Fatal error: Couldn't find \WhatsNew. on WhatsNew with fields [SwiftData.Schema.PropertyMetadata(name: "serverID", keypath: \WhatsNew., defaultValue: nil, metadata: Optional(Attribute - name: , options: [unique], valueType: Any, defaultValue: nil, hashModifier: nil)), SwiftData.Schema.PropertyMetadata(name: "title", keypath: \WhatsNew., defaultValue: nil, metadata: nil), SwiftData.Schema.PropertyMetadata(name: "bulletPoints", keypath: \WhatsNew.)>, defaultValue: nil, metadata: nil), SwiftData.Schema.PropertyMetadata(name: "dateDescription", keypath: \WhatsNew., defaultValue: nil, metadata: nil), SwiftData.Schema.PropertyMetadata(name: "readAt", keypath: \WhatsNew.)>, defaultValue: nil, metadata: nil)] It seems (cannot confirm) that something in the release build optimization process is stripping out some metadata / something about these models that makes this predicate crash. Tested on iOS 18.0 and 18.1 beta. How can I resolve this? I have two dozen types that conform to this protocol. I could manually specialize this function for every type myself but... ugh.
2
2
1.4k
Oct ’25
Can an app have multiple widget extensions?
Is there a problem with an app having more than one widget extension? I previously had two 'Today View' extensions that I'm replacing but after installing the app on device with two widget extensions, I'm only seeing the second one in the widget picker. I see that there's WidgetBundle but my two widgets have very different datasets so the timeline stuff won't mesh.
4
0
7.5k
Oct ’22
Xcode 12 Framework: 'Double-quoted include in framework header, expected angle-bracketed instead'
I've got an iOS framework that I've had around for ages. It's a mixture of Objective-C and Swift. Since installing Xcode 12, I'm now getting a bunch of warnings of the type: 'Double-quoted include in framework header, expected angle-bracketed instead' If I go to the various source files and say change: #import "Place.h" to #import &lt;VegasKit/Place.h&gt; then I get an error saying it can't find the file. If I try this: #import &lt;Place.h&gt; then I get an error telling me to go back to double-quotes, i.e. undo the change. Any idea what I can do to get this all setup correctly? Thanks.
18
1
31k
Oct ’23
CSUserQuery Generating Model Load Failure - No Results
I'm trying CoreSpotlight on the 18b1 seed on iOS and after submitting my query, I'm getting multiple errors about what looks like missing models: [Model loading] model loading failed with err -1000 for model path /Users/hunter/Library/Developer/CoreSimulator/Devices/0AF4F46E-5510-4458-B61C-F8A153155809/data/Containers/Data/Application/1D8580C0-AC80-4949-9FDA-31DB463BDA5C/Library/Spotlight/Resources_V3/Default/models/spotlight_l2.mlmodelc and directives path /Users/hunter/Library/Developer/CoreSimulator/Devices/0AF4F46E-5510-4458-B61C-F8A153155809/data/Containers/Data/Application/1D8580C0-AC80-4949-9FDA-31DB463BDA5C/Library/Spotlight/Resources_V3/Default/directives/directives_l2.mdplist I am calling CSUserQuery.prepare() but that doesn't seem to make a difference. Is there more to this than what is on this page? https://developer.apple.com/documentation/corespotlight/building-a-search-interface-for-your-app?changes=latest_minor
3
1
877
Jul ’24
SwiftData "Batch Delete" Fails With NSCoreDataOptimisticLockingFailure
I am trying to use the ModelContainer's "delete" function to delete all instances of a model but I'm getting an error related to my relationships: Constraint trigger violation: Batch delete failed due to mandatory OTO nullify inverse on LeagueSeasonRanking/golfer I do have a relationship on Golfer, a toMany relationship to LeagueSeasonRanking which is marked with a cascade delete rule... I would expect that to take care of things and cascade along but it seems to not work. Is that a bug?
0
1
539
Aug ’24
SwiftData: SwiftData.PersistentIdentifierImplementation) was remapped to a temporary identifier during save
I'm seeing a lot of these in my logs: PersistentIdentifier PersistentIdentifier(id: SwiftData.PersistentIdentifier.ID(url: x-swiftdata://Course/BC9CF99A-DE6A-46F1-A18D-8034255A56D8), implementation: SwiftData.PersistentIdentifierImplementation) was remapped to a temporary identifier during save: PersistentIdentifier(id: SwiftData.PersistentIdentifier.ID(url: x-coredata:///Course/t58C849CD-D895-4773-BF53-3F63CF48935B210), implementation: SwiftData.PersistentIdentifierImplementation). This is a fatal logic error in DefaultStore ... though everything seems to work. Does anyone know what this means in this context? Anything I can do to not have this appear?
9
8
1.8k
May ’25
Do we need *both* associateAppEntity and to implement attributeSet when indexing App Entities?
I am working on adding indexing to my App Entities via IndexedEntity. I already, separately index my content via Spotlight. Watching 'What's New in App Intents', this is covered well but I have a question. Do I need to implement both CSSearchableItem's associateAppEntity AND also a custom implementation of attributeSet in my IndexedEntity conformance? It seems duplicative but I can't tell from the video if you're supposed to do both or just one or the other.
1
1
611
Nov ’24