Concurrency

RSS for tag

Concurrency is the notion of multiple things happening at the same time.

Posts under Concurrency tag

162 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Coordination of Video Capture and Audio Engine Start in iOS Development
Question: When implementing simultaneous video capture and audio processing in an iOS app, does the order of starting these components matter, or can they be initiated in any sequence? I have an actor responsible for initiating video capture using the setCaptureMode function. In this actor, I also call startAudioEngine to begin the audio engine and register a resultObserver. While the audio engine starts successfully, I notice that the resultObserver is not invoked when startAudioEngine is called synchronously. However, it works correctly when I wrap the call in a Task. Could you please explain why the synchronous call to startAudioEngine might be blocking the invocation of the resultObserver? What would be the best practice for ensuring both components work effectively together? Additionally, if I were to avoid using Task, what approach would be required? Lastly, is the startAudioEngine effective from the start time of the video capture (00:00)? Platform: Xcode 16, Swift 6, iOS 18 References: Classifying Sounds in an Audio Stream – In my case, the analyzeAudio() method is not invoked. Setting Up a Capture Session – Here, the focus is on video capture. Classifying Sounds in an Audio File Code Snippet: (For further details. setVideoCaptureMode() surfaces the problem.) // ensures all operations happen off of the `@MainActor`. actor CaptureService { ... nonisolated private let resultsObserver1 = ResultsObserver1() ... private func setUpSession() throws { .. } ... setVideoCaptureMode() throws { captureSession.beginConfiguration() defer { captureSession.commitConfiguration() } /* -- Works fine (analyseAudio is printed) Task { self.resultsObserver1.startAudioEngine() } */ self.resultsObserver1.startAudioEngine() // Does not work - analyzeAudio not printed captureSession.sessionPreset = .high try addOutput(movieCapture.output) if isHDRVideoEnabled { setHDRVideoEnabled(true) } updateCaptureCapabilities() }
5
0
377
Oct ’24
MPMediaItemPropertyArtwork crashes on Swift 6
Hey all! in my personal quest to make future proof apps moving to Swift 6, one of my app has a problem when setting an artwork image in MPNowPlayingInfoCenter Here's what I'm using to set the metadata func setMetadata(title: String? = nil, artist: String? = nil, artwork: String? = nil) async throws { let defaultArtwork = UIImage(named: "logo")! var nowPlayingInfo = [ MPMediaItemPropertyTitle: title ?? "***", MPMediaItemPropertyArtist: artist ?? "***", MPMediaItemPropertyArtwork: MPMediaItemArtwork(boundsSize: defaultArtwork.size) { _ in defaultArtwork } ] as [String: Any] if let artwork = artwork { guard let url = URL(string: artwork) else { return } let (data, response) = try await URLSession.shared.data(from: url) guard (response as? HTTPURLResponse)?.statusCode == 200 else { return } guard let image = UIImage(data: data) else { return } nowPlayingInfo[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: image.size) { _ in image } } MPNowPlayingInfoCenter.default().nowPlayingInfo = nowPlayingInfo } the app crashes when hitting MPMediaItemPropertyArtwork: MPMediaItemArtwork(boundsSize: defaultArtwork.size) { _ in defaultArtwork } or nowPlayingInfo[MPMediaItemPropertyArtwork] = MPMediaItemArtwork(boundsSize: image.size) { _ in image } commenting out these two make the app work again. Again, no clue on why. Thanks in advance
6
0
506
Oct ’24
Problem with NSSound playback in XPC service
Hello, I run into an issue on Monterey (12.7.5). I have a bundled XPC service in my application which is displaying some stuff and playin sounds via NSSound. I had a problem with playback due to service priority, so I use the trick with a reply block where I send a reply block to the service and basically just retain it and never call it. This worked fine so far, but we have users, predominantly on Monterey, who are having a problem with sound playback. It's choppy and distorted when their machine is under load (where "load" often just means playing a video on YouTube in Chrome). Is there anything else I can do to get the proper priority for my xpc service so I can avoid distorted sound? Additionally the service type is Application and RunLoopType is NSRunLoop with JoinExistingSession set to true. The QoS level of main queue is 0x21 (user interactive) and I'm calling all the NSSound APIs on main queue.
3
0
381
Oct ’24
Request authorization for the notification center crash iOS app on Swift 6
Hey all! During the migration of a production app to swift 6, I've encountered a problem: when hitting the UNUserNotificationCenter.current().requestAuthorization the app crashes. If I switch back to Language Version 5 the app works as expected. The offending code is defined here class AppDelegate: NSObject, UIApplicationDelegate { func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { FirebaseApp.configure() FirebaseConfiguration.shared.setLoggerLevel(.min) UNUserNotificationCenter.current().delegate = self let authOptions: UNAuthorizationOptions = [.alert, .badge, .sound] UNUserNotificationCenter.current().requestAuthorization(options: authOptions) { _, _ in } application.registerForRemoteNotifications() Messaging.messaging().delegate = self return true } } The error is depicted here: I have no idea how to fix this. Any help will be really appreciated thanks in advance
13
2
1.1k
1w
Stored property 'base' of 'Sendable'-conforming struct 'AnyShape' has non-sendable type '(CGRect) -> Path'; this is an error in the Swift 6 language mode
Since I updated my project I'm getting this error Stored property 'base' of 'Sendable'-conforming struct 'AnyShape' has non-sendable type '(CGRect) -> Path'; this is an error in the Swift 6 language mode I get this error at that struct, more specifically on the base variable public struct AnyShape: Shape { private var base: (CGRect) -> Path public init<S: Shape>(shape: S) { base = shape.path(in:) } public func path(in rect: CGRect) -> Path { base(rect) } } I have no idea how to solve this issue, I've been looking on the internet for same issues and get nothing yet
1
0
457
Sep ’24
Swift Concurrency crash in iOS 18 and 18.1 in withTaskCancellationHandler
We are seeing a swift concurrency related crash in iOS 18 and iOS 18.1 that has no direct link to any part of my code base in the stack trace. We are not able to reproduce locally but see it in the Organizer. The crash seems to come from withTaskCancellationHandler in Concurrency.swift Incident Identifier: C5331198-3922-471F-8E39-57186BBB962B Distributor ID: com.apple.AppStore Hardware Model: iPhone16,2 Process: MyApp [866] Path: /private/var/containers/Bundle/Application/B320C8CF-5711-4F14-92C4-0693420DDE07/MyApp.app/MyApp Identifier: com.MyApp.release Version: 10.0.1 (1) AppStoreTools: 16A242b AppVariant: 1:iPhone16,2:18 Code Type: ARM-64 (Native) Role: Foreground Parent Process: launchd [1] Coalition: com.MyApp.release [989] Date/Time: 2024-09-21 06:30:38.3210 -0500 Launch Time: 2024-09-21 06:18:03.0691 -0500 OS Version: iPhone OS 18.1 (22B5007p) Release Type: Beta Baseband Version: 2.15.01 Report Version: 104 Exception Type: EXC_BAD_ACCESS (SIGSEGV) Exception Subtype: KERN_INVALID_ADDRESS at 0x0000000000000004 Exception Codes: 0x0000000000000001, 0x0000000000000004 VM Region Info: 0x4 is not in any region. Bytes before following region: 4340908028 REGION TYPE START - END [ VSIZE] PRT/MAX SHRMOD REGION DETAIL UNUSED SPACE AT START ---> __TEXT 102bd0000-102be0000 [ 64K] r-x/r-x SM=COW /var/containers/Bundle/Application/B320C8CF-5711-4F14-92C4-0693420DDE07/MyApp.app/MyApp Termination Reason: SIGNAL 11 Segmentation fault: 11 Terminating Process: exc handler [866] Triggered by Thread: 3 Thread 3 Crashed: 0 MyApp 0x0000000103b00b8c withTaskCancellationHandler<A>(operation:onCancel:isolation:) + 108 (/<compiler-generated>:0) 1 MyApp 0x0000000103b0284d closure #1 in DataRequest.dataTask<A>(automaticallyCancelling:forResponse:) + 1 (Concurrency.swift:352) 2 MyApp 0x0000000102f66011 partial apply for closure #1 in closure #1 in variable initialization expression of static FireAndForgetKey.liveValue + 1 3 MyApp 0x0000000102f80841 closure #1 in DataTask.response.getter + 1 4 MyApp 0x0000000102f66011 partial apply for closure #1 in closure #1 in variable initialization expression of static FireAndForgetKey.liveValue + 1 5 libswift_Concurrency.dylib 0x000000019164e689 completeTaskWithClosure(swift::AsyncContext*, swift::SwiftError*) + 1 (Task.cpp:471)
4
0
1.2k
Sep ’24
Sending main actor-isolated value of type 'PurchaseAction' with later accesses to nonisolated context risks causing data races
Trying to migrate to Swift 6. However getting this error when using SwiftUI StoreKit purchase environment. Sending main actor-isolated value of type 'PurchaseAction' with later accesses to nonisolated context risks causing data races @Environment(\.purchase) private var purchase let result = try await purchase(product)
1
0
390
Sep ’24
Live activity sample code for Swift 6?
Hi, I'm updating our app to use Xcode 16 and Swift 6 language mode. I'm stuck on updating our live activity code. I looked at the Emoji Rangers sample project and after switching it to Swft 6 mode, it has the exact same errors as our project. The main problem seems to be that Activity is not Sendable, which prevents us from passing it to child tasks to await things like activityStateUpdates and contentUpdates (those are also not Sendable). Is there any guidance on this? Updated sample code? Another project?
4
0
367
Sep ’24
iOS18 AVPlayerViewController 出现卡住界面
(AVPlayerViewController *)avPlayerVC { if(!_avPlayerVC){ _avPlayerVC =[[AVPlayerViewController alloc] init]; _avPlayerVC.videoGravity = AVLayerVideoGravityResizeAspectFill; _avPlayerVC.showsPlaybackControls = NO; [self addSubview:_avPlayerVC.view]; [_avPlayerVC.view mas_makeConstraints:^(MASConstraintMaker *make) { make.edges.mas_equalTo(0); }]; [self sendSubviewToBack:_avPlayerVC.view]; } return _avPlayerVC; } 我在一个cell里添加这个,界面无法动弹。只有在iOS18会这样
2
1
328
Sep ’24
Swift 6 Migration error in Sample code (Updating an app to use strict concurrency sample code) provided by Apple.
Updating an app to use strict concurrency is not compiling in Swift 6 with strict concurrency enabled. I am getting the following error in Xcode Version 16.0 (16A242d). private func queryHealthKit() async throws -&gt; ( [HKSample]?, [HKDeletedObject]?, HKQueryAnchor? ) { try await withCheckedThrowingContinuation { continuation in // Create a predicate that returns only samples created within the last 24 hours. let endDate = Date() let startDate = endDate.addingTimeInterval(-24.0 * 60.0 * 60.0) let datePredicate = HKQuery.predicateForSamples( withStart: startDate, end: endDate, options: [.strictStartDate, .strictEndDate]) // Create the query. let query = HKAnchoredObjectQuery( type: caffeineType, predicate: datePredicate, anchor: anchor, limit: HKObjectQueryNoLimit ) { (_, samples, deletedSamples, newAnchor, error) in // When the query ends, check for errors. if let error { continuation.resume(throwing: error) } else { continuation.resume(returning: (samples, deletedSamples, newAnchor)) } } store.execute(query) } } The error is on ** continuation.resume(returning: (samples, deletedSamples, newAnchor)) ** and the error is Task-isolated value of type '([HKSample]?, [HKDeletedObject]?, HKQueryAnchor?)' passed as a strongly transferred parameter; later accesses could race. How to solve this error?
2
1
666
Sep ’24
How to fix this Swift 6 migration issue?
Here is a code snippet about AVPlayer. avPlayer.addPeriodicTimeObserver(forInterval: CMTime(value: 1, timescale: 60), queue: .main) { [weak self] _ in // Call main actor-isolated instance methods } Xcode shows warnings that Call to main actor-isolated instance method '***' in a synchronous nonisolated context; this is an error in the Swift 6 language mode. How can I fix this? avPlayer.addPeriodicTimeObserver(forInterval: CMTime(value: 1, timescale: 60), queue: .main) { [weak self] _ in Task { @MainActor in // Call main actor-isolated instance methods } } Can I use this solution above? But it seems switching actors frequently can slow down performance.
1
0
885
Sep ’24
Live queries on SwiftData DB but without @Query macro?
I switched from using @Query to @ModelActor because of the following reasons: Performance Issues: With @Query, my app became unresponsive with large datasets because data fetching occurred on the main thread. Integration with CKSyncEngine: I needed to implement @ModelActor anyway to allow CKSyncEngine to add data to local persistent storage from the background. In my current setup, the onAppear() method for my view calls the getItems() function on my model actor, which returns [ItemsDTO] and then View renders them. However, I'm now facing a challenge in achieving the same automatic data refreshing and view updates that @Query provided. Here are a few potential solutions I'm considering: Periodic Data Fetching: Fetch data at regular intervals to keep the view updated. But this seems expensive. Local Write Monitoring: Monitor all local writes to automatically trigger updates when changes occur. But this is quite a lot of code I would have to write myself. Switch to manual refresh: Users would have to manually trigger UI updates by pressing button. Reintroduce @Query: Writes would happen from ModelActor, but reads would still happen from Main thread. But then again app would become unresponsive on reads. If you have any additional ideas or best practices for maintaining reactivity with @ModelActor, I'd love to hear them!
1
1
460
Sep ’24
Issues with @preconcurrency and AVFoundation in Swift 6 on Xcode 16.1/iOS 18 (Worked fine in Swift 5)
Question: I'm working on a project in Xcode 16.1, using Swift 6 with iOS 18. My code is working fine in Swift 5, but I'm running into concurrency issues when upgrading to Swift 6, particularly with the @preconcurrency attribute in AVFoundation. Here is the relevant part of my code: import SwiftUI @preconcurrency import AVFoundation struct OverlayButtonBar: View { ... let audioTracks = await loadTracks(asset: asset, mediaType: .audio) ... // Tracks are extracted before crossing concurrency boundaries private func loadTracks(asset: AVAsset, mediaType: AVMediaType) async -> [AVAssetTrack] { do { return try await asset.load(.tracks).filter { $0.mediaType == mediaType } } catch { print("Error loading tracks: \(error)") return [] } } } Issues: When using @preconcurrency, I get the warning: @preconcurrency attribute on module AVFoundation has no effect. Suggested fix by Xcode is: Remove @preconcurrency. But if I remove @preconcurrency, I get both a warning and an error: Warning: Add '@preconcurrency' to treat 'Sendable'-related errors from module 'AVFoundation' as warnings. Error: Non-sendable type [AVAssetTrack] returned by implicitly asynchronous call to nonisolated function cannot cross actor boundary. (Class AVAssetTrack does not conform to the Sendable protocol (AVFoundation.AVAssetTrack)). This error comes if I attempt to directly access non-Sendable AVAssetTrack in an async context : let audioTracks = await loadTracks(asset: asset, mediaType: .audio) How can I resolve this issue while staying compliant with Swift 6 concurrency rules? Is there a recommended approach to handling non-Sendable types like AVAssetTrack in concurrency contexts? Appreciate any guidance on making this work in Swift 6, especially considering it worked fine in Swift 5. Thanks in advance!
1
0
821
Sep ’24
Handling Main Actor-Isolated Values with `PHPhotoLibrary` in Swift 6
Hello, I’m encountering an issue with the PHPhotoLibrary API in Swift 6 and iOS 18. The code I’m using worked fine in Swift 5, but I’m now seeing the following error: Sending main actor-isolated value of type '() -> Void' with later accesses to nonisolated context risks causing data races Here is the problematic code: Button("Save to Camera Roll") { saveToCameraRoll() } ... private func saveToCameraRoll() { guard let overlayFileURL = mediaManager.getOverlayURL() else { return } Task { do { let status = await PHPhotoLibrary.requestAuthorization(for: .addOnly) guard status == .authorized else { return } try await PHPhotoLibrary.shared().performChanges({ if let creationRequest = PHAssetCreationRequest.creationRequestForAssetFromVideo(atFileURL: overlayFileURL) { creationRequest.creationDate = Date() } }) await MainActor.run { saveSuccessMessage = "Video saved to Camera Roll successfully" } } catch { print("Error saving video to Camera Roll: \(error.localizedDescription)") } } } Problem Description: The error message suggests that a main actor-isolated value of type () -> Void is being accessed in a nonisolated context, potentially leading to data races. This issue arises specifically at the call to PHPhotoLibrary.shared().performChanges. Questions: How can I address the data race issues related to main actor isolation when using PHPhotoLibrary.shared().performChanges? What changes, if any, are required to adapt this code for Swift 6 and iOS 18 while maintaining thread safety and actor isolation? Are there any recommended practices for managing main actor-isolated values in asynchronous operations to avoid data races? I appreciate any points or suggestions to resolve this issue effectively. Thank you!
1
0
745
Sep ’24
Inexplicable Fence Hang
Hello, My App is getting a Fence hang right after install in a specific scenario. Issue1: I attempted to follow the directions, tried to symbolicate the file etc. however did not have much luck. I was able to pinpoint the lines of code where the hang seems to occur. I did this using simple print and comment out/uncomment blocks of code related to the specific scenario. I was able to do so as, not much is happening on the Main thread in this scenario . Issue 2: The following lines of code ( modified var etc. ) seem to cause the hang. Commenting them out gets rid of the hang across devices, while online/offline etc. I am not sure if I need to use a framework other than AVFoundation. Note: The file extension is mpg The music files are static ( included in the Bundle ) and not accessed from user's playlist etc. import var plyr : AVAudioPlayer? let pth = Bundle.main.path(forResource: "MusicFileName", ofType: "mpg")! let url = URL(fileURLWithPath: pth) do [{](https://www.example.com/) plyr = try AVAudioPlayer(contentsOf: url) plyr?.prepareToPlay() plyr?.play() } catch { // print error etc. } Thanks in advance. I would appreciate some help! Close to submission :)
6
0
460
Sep ’24
Xcode 16 beta 6 - unexpected concurrency build issues
The following behavior seems like a bug in the swift compiler that ships with Xcode 16 beta 6. Add the following code snippet to a new iOS app project using Xcode 16 beta 6 and observe the error an warning called out in the comments within the itemProvider() method: import WebKit extension WKWebView { func allowInspectionForDebugBuilds() { // commenting out the following line makes it so that the completion closure argument of the trailing closure // passed to NSItemProvider.registerDataRepresentation(forTypeIdentifier:visibility:loadHandler:) is no longer // isolated to the main actor, thus resolving the build issues. It is unexpected that the presence or absence of // the following line would have this kind of impact. isInspectable = true } } class Foo { func itemProvider() -> NSItemProvider? { let itemProvider = NSItemProvider() itemProvider.registerDataRepresentation(forTypeIdentifier: "", visibility: .all) { completion in Task.detached { guard let url = URL(string: "") else { completion(nil, NSError()) // error: Expression is 'async' but is not marked with 'await' return } let task = URLSession.shared.dataTask(with: url) { data, _, error in completion(data, error) // warning: Call to main actor-isolated parameter 'completion' in a synchronous nonisolated context; this is an error in the Swift 6 language mode } task.resume() } return Progress() } return itemProvider } } Now, comment out the line isInspectable = true and observe that the error and warning disappear. Also filed as FB14783405 and https://github.com/swiftlang/swift/issues/76171 Hoping to see this fixed before Xcode 16 stable.
8
0
690
Sep ’24
withCheckedContinuation crashes on Xcode 16
We are using a 3rd party SDK which crashes on iOS 18 in certain scenarios. They say they need Apple to fix this bug ahead of release https://github.com/swiftlang/swift/issues/75952 but I'm skeptical since it is only a few weeks away most likely. The bug seems pretty bad so is there any chance it will be fixed before iOS 18? We aim for a same-day release so would be great to know if we need to remove the 3rd party SDK or not.
5
1
1.5k
Sep ’24
AVAudioPlayerNode scheduleBuffer & Swift 6 Concurrency
We do custom audio buffering in our app. A very minimal version of the relevant code would look something like: import AVFoundation class LoopingBuffer { private var playerNode: AVAudioPlayerNode private var audioFile: AVAudioFile init(playerNode: AVAudioPlayerNode, audioFile: AVAudioFile) { self.playerNode = playerNode self.audioFile = audioFile } func scheduleBuffer(_ frames: AVAudioFrameCount) async { let audioBuffer = AVAudioPCMBuffer( pcmFormat: audioFile.processingFormat, frameCapacity: frames )! try! audioFile.read(into: audioBuffer, frameCount: frames) await playerNode.scheduleBuffer(audioBuffer, completionCallbackType: .dataConsumed) } } We are in the migration process to swift 6 concurrency and have moved a lot of our audio code into a global actor. So now we have something along the lines of import AVFoundation @globalActor public actor AudioActor: GlobalActor { public static let shared = AudioActor() } @AudioActor class LoopingBuffer { private var playerNode: AVAudioPlayerNode private var audioFile: AVAudioFile init(playerNode: AVAudioPlayerNode, audioFile: AVAudioFile) { self.playerNode = playerNode self.audioFile = audioFile } func scheduleBuffer(_ frames: AVAudioFrameCount) async { let audioBuffer = AVAudioPCMBuffer( pcmFormat: audioFile.processingFormat, frameCapacity: frames )! try! audioFile.read(into: audioBuffer, frameCount: frames) await playerNode.scheduleBuffer(audioBuffer, completionCallbackType: .dataConsumed) } } Unfortunately this now causes an error: error: sending 'audioBuffer' risks causing data races | `- note: sending global actor 'AudioActor'-isolated 'audioBuffer' to nonisolated instance method 'scheduleBuffer(_:completionCallbackType:)' risks causing data races between nonisolated and global actor 'AudioActor'-isolated uses I understand the error, what I don't understand is how I can safely use this API? AVAudioPlayerNode is not marked as @MainActor so it seems like it should be safe to schedule a buffer from a custom actor as long as we don't send it anywhere else. Is that right? AVAudioPCMBuffer is not Sendable so I don't think it's possible to make this callsite ever work from an isolated context. Even forgetting about the custom actor, if you instead annotate the class with @MainActor the same error is still present. I think the AVAudioPlayerNode.scheduleBuffer() function should have a sending annotation to make clear that the buffer can't be used after it's sent. I think that would make the compiler happy but I'm not certain. Am I overlooking something, holding it wrong, or is this API just pretty much unusable in Swift 6? My current workaround is just to import AVFoundation with @preconcurrency but it feels dirty and I am worried there may be a real issue here that I am missing in doing so.
3
0
502
Aug ’24
SwiftData @ModelActor Memory usage skyrocketing when changing properties
When changing a property of a SwiftData Model from a ModelActor the memory needed slightly increases. Once you do that more often, you can see that the usage is linearly increasing. I modified the Swiftdata template as little as possible. This is the least code I need to reproduce the problem: Changes In the @main struct : ContentView(modelContainer: sharedModelContainer) ContentView: struct ContentView: View { @Query private var items: [Item] let dataHanndler: DataHandler @State var timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: false, block: { t in }) var body: some View { NavigationSplitView { List { ForEach(items) { item in NavigationLink { Text("Item at \(item.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard))") } label: { Text(item.timestamp, format: Date.FormatStyle(date: .numeric, time: .standard)) } } } .toolbar { ToolbarItem(placement: .navigationBarTrailing) { EditButton() } ToolbarItem { Button(action: addItem) { Label("Add Item", systemImage: "plus") } } ToolbarItem { Button { timer = Timer.scheduledTimer(withTimeInterval: 0.1, repeats: true) { t in Task { await dataHanndler.updateRandom() // Obviously this makes little sense but I need to update a lot of entities in my actual app. This is the simplest way to demonstrate that. updateRandom() could also be a function of a view but that doesn't make a difference } } } label: { Label("Do a lot of writing", systemImage: "gauge.with.dots.needle.100percent") } } ToolbarItem { Button { timer.invalidate() } label: { Label("Invalidate", systemImage: "stop.circle") } } } } detail: { Text("Select an item") } } private func addItem() { Task { await dataHanndler.insert(timestamp: Date.now) } } init(modelContainer: ModelContainer) { self.dataHanndler = DataHandler(modelContainer: modelContainer) } } ModelActor: @ModelActor actor DataHandler { public func update<T>(_ persistentIdentifier: PersistentIdentifier, keypath: ReferenceWritableKeyPath<Item, T>, to value: T) throws { let model = modelContext.model(for: persistentIdentifier) as! Item model[keyPath: keypath] = value } public func insert(timestamp: Date) { let item = Item(timestamp: timestamp) modelContext.insert(item) } public func updateRandom() { let count = try! modelContext.fetchCount(FetchDescriptor<Item>()) var descriptor = FetchDescriptor<Item>() descriptor.fetchOffset = Int.random(in: 0..<count) descriptor.fetchLimit = 1 let model = try! modelContext.fetch(descriptor) model.first!.timestamp = Date.now } } I filed a bug report FB14876920 but I am looking for other ideas to solve this before it will be fixed in a future update. The modelContext I use is created and managed by the @ModelActor macro. Happy to hear ideas
2
0
398
Aug ’24
Swift Data + Swift 6 Sendable-ity paradox
Xcode 16 beta 3 Assume a SwiftData model starts like this and has a few more properties like a name and creation date (these are immaterial to my main question. @Model final class Batch: Identifiable, Sendable { @Attribute(.unique) var id: UUID //... more stuff The combination of Swift 6 (or Swift 5 with warnings enabled) and SwiftData seem to provide a paradox: Swift 6 complains when the id is a let: Cannot expand accessors on variable declared with 'let'; this is an error in the Swift 6 language mode Swift 6 complains when the id is a var: Stored property '_id' of 'Sendable'-conforming class 'Batch' is mutable; this is an error in the Swift 6 language mode Removing "Sendable" may be one solution but defeats the purpose and causes warnings elsewhere in the app about the model not being Sendable. Is there an obvious fix? Am I as a newbie (to the combination of Swift 6 and SwiftData) missing an entire architectural step of using ModelActor somewhere?
1
1
1.2k
Aug ’24