Concurrency

RSS for tag

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

Posts under Concurrency tag

174 Posts
Sort by:

Post

Replies

Boosts

Views

Activity

Concurrency Resources
Swift Concurrency Resources: DevForums tags: Concurrency The Swift Programming Language > Concurrency documentation Migrating to Swift 6 documentation WWDC 2022 Session 110351 Eliminate data races using Swift Concurrency — This ‘sailing on the sea of concurrency’ talk is a great introduction to the fundamentals. WWDC 2021 Session 10134 Explore structured concurrency in Swift — The table that starts rolling out at around 25:45 is really helpful. Swift Async Algorithms package Swift Concurrency Proposal Index DevForum post Why is flow control important? DevForums post Matt Massicotte’s blog Dispatch Resources: DevForums tags: Dispatch Dispatch documentation — Note that the Swift API and C API, while generally aligned, are different in many details. Make sure you select the right language at the top of the page. Dispatch man pages — While the standard Dispatch documentation is good, you can still find some great tidbits in the man pages. See Reading UNIX Manual Pages. Start by reading dispatch in section 3. WWDC 2015 Session 718 Building Responsive and Efficient Apps with GCD [1] WWDC 2017 Session 706 Modernizing Grand Central Dispatch Usage [1] Avoid Dispatch Global Concurrent Queues DevForums post Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com" [1] These videos may or may not be available from Apple. If not, the URL should help you locate other sources of this info.
0
0
1.2k
Dec ’24
SwiftUI crashes EXC_BREAKPOINT at _dispatch_semaphore_dispose
Based on crash reports for our app in production, we're seeing these SwiftUI crashes but couldn't figure out why it is there. These crashes are pretty frequent (>20 crashed per day). Would really appreciate it if anyone has any insight on why this happens. Based on the stacktrace, i can't really find anything that links back to our app (replaced with MyApp in the stacktrace). Thank you in advance! Crashed: com.apple.main-thread 0 libdispatch.dylib 0x39dcc _dispatch_semaphore_dispose.cold.1 + 40 1 libdispatch.dylib 0x4c1c _dispatch_semaphore_signal_slow + 82 2 libdispatch.dylib 0x2d30 _dispatch_dispose + 208 3 SwiftUICore 0x77f788 destroy for StoredLocationBase.Data + 64 4 libswiftCore.dylib 0x3b56fc swift_arrayDestroy + 196 5 libswiftCore.dylib 0x13a60 UnsafeMutablePointer.deinitialize(count:) + 40 6 SwiftUICore 0x95f374 AtomicBuffer.deinit + 124 7 SwiftUICore 0x95f39c AtomicBuffer.__deallocating_deinit + 16 8 libswiftCore.dylib 0x3d783c _swift_release_dealloc + 56 9 libswiftCore.dylib 0x3d8950 bool swift::RefCounts<swift::RefCountBitsT<(swift::RefCountInlinedness)1>>::doDecrementSlow<(swift::PerformDeinit)1>(swift::RefCountBitsT<(swift::RefCountInlinedness)1>, unsigned int) + 160 10 SwiftUICore 0x77e53c StoredLocation.deinit + 32 11 SwiftUICore 0x77e564 StoredLocation.__deallocating_deinit + 16 12 libswiftCore.dylib 0x3d783c _swift_release_dealloc + 56 13 libswiftCore.dylib 0x3d8950 bool swift::RefCounts<swift::RefCountBitsT<(swift::RefCountInlinedness)1>>::doDecrementSlow<(swift::PerformDeinit)1>(swift::RefCountBitsT<(swift::RefCountInlinedness)1>, unsigned int) + 160 14 MyApp 0x1673338 objectdestroyTm + 6922196 15 libswiftCore.dylib 0x3d783c _swift_release_dealloc + 56 16 libswiftCore.dylib 0x3d8950 bool swift::RefCounts<swift::RefCountBitsT<(swift::RefCountInlinedness)1>>::doDecrementSlow<(swift::PerformDeinit)1>(swift::RefCountBitsT<(swift::RefCountInlinedness)1>, unsigned int) + 160 17 SwiftUICore 0x650290 _AppearanceActionModifier.MergedBox.__deallocating_deinit + 32 18 libswiftCore.dylib 0x3d783c _swift_release_dealloc + 56 19 libswiftCore.dylib 0x3d8950 bool swift::RefCounts<swift::RefCountBitsT<(swift::RefCountInlinedness)1>>::doDecrementSlow<(swift::PerformDeinit)1>(swift::RefCountBitsT<(swift::RefCountInlinedness)1>, unsigned int) + 160 20 SwiftUICore 0x651b44 closure #1 in _AppearanceActionModifier.MergedBox.update()partial apply + 28 21 libswiftCore.dylib 0x3d783c _swift_release_dealloc + 56 22 libswiftCore.dylib 0x3d8950 bool swift::RefCounts<swift::RefCountBitsT<(swift::RefCountInlinedness)1>>::doDecrementSlow<(swift::PerformDeinit)1>(swift::RefCountBitsT<(swift::RefCountInlinedness)1>, unsigned int) + 160 23 libswiftCore.dylib 0x3b56fc swift_arrayDestroy + 196 24 libswiftCore.dylib 0xa2a54 _ContiguousArrayStorage.__deallocating_deinit + 96 25 libswiftCore.dylib 0x3d783c _swift_release_dealloc + 56 26 libswiftCore.dylib 0x3d8950 bool swift::RefCounts<swift::RefCountBitsT<(swift::RefCountInlinedness)1>>::doDecrementSlow<(swift::PerformDeinit)1>(swift::RefCountBitsT<(swift::RefCountInlinedness)1>, unsigned int) + 160 27 SwiftUICore 0x4a6c4c type metadata accessor for _ContiguousArrayStorage<CVarArg> + 120 28 libswiftCore.dylib 0x3d783c _swift_release_dealloc + 56 29 libswiftCore.dylib 0x3d8950 bool swift::RefCounts<swift::RefCountBitsT<(swift::RefCountInlinedness)1>>::doDecrementSlow<(swift::PerformDeinit)1>(swift::RefCountBitsT<(swift::RefCountInlinedness)1>, unsigned int) + 160 30 SwiftUICore 0x4a5d88 static Update.dispatchActions() + 1332 31 SwiftUICore 0xa0db28 closure #2 in closure #1 in ViewRendererHost.render(interval:updateDisplayList:targetTimestamp:) + 132 32 SwiftUICore 0xa0d928 closure #1 in ViewRendererHost.render(interval:updateDisplayList:targetTimestamp:) + 708 33 SwiftUICore 0xa0b0d4 ViewRendererHost.render(interval:updateDisplayList:targetTimestamp:) + 556 34 SwiftUI 0x8f1634 UIHostingViewBase.renderForPreferences(updateDisplayList:) + 168 35 SwiftUI 0x8f495c closure #1 in UIHostingViewBase.requestImmediateUpdate() + 72 36 SwiftUI 0xcc700 thunk for @escaping @callee_guaranteed () -> () + 36 37 libdispatch.dylib 0x2370 _dispatch_call_block_and_release + 32 38 libdispatch.dylib 0x40d0 _dispatch_client_callout + 20 39 libdispatch.dylib 0x129e0 _dispatch_main_queue_drain + 980 40 libdispatch.dylib 0x125fc _dispatch_main_queue_callback_4CF + 44 41 CoreFoundation 0x56204 __CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE__ + 16 42 CoreFoundation 0x53440 __CFRunLoopRun + 1996 43 CoreFoundation 0x52830 CFRunLoopRunSpecific + 588 44 GraphicsServices 0x11c4 GSEventRunModal + 164 45 UIKitCore 0x3d2eb0 -[UIApplication _run] + 816 46 UIKitCore 0x4815b4 UIApplicationMain + 340 47 SwiftUI 0x101f98 closure #1 in KitRendererCommon(_:) + 168 48 SwiftUI 0xe2664 runApp<A>(_:) + 100 49 SwiftUI 0xe5490 static App.main() + 180 50 MyApp 0x8a7828 main + 4340250664 (MyApp.swift:4340250664) 51 ??? 0x1ba496ec8 (Missing)
0
0
69
1d
Non-sendable type AVMediaSelectionGroup
Hi all, we try migrate project to Swift 6 Project use AVPlayer in MainActor Selection audio and subtitiles not work Task { @MainActor in let group = try await item.asset.loadMediaSelectionGroup(for: AVMediaCharacteristic.audible) get error: Non-sendable type 'AVMediaSelectionGroup?' returned by implicitly asynchronous call to nonisolated function cannot cross actor boundary and second example `if #available(iOS 15.0, *) { player?.currentItem?.asset.loadMediaSelectionGroup(for: AVMediaCharacteristic.audible, completionHandler: { group, error in if error != nil { return } if let groupWrp = group { DispatchQueue.main.async { self.setupAudio(groupWrp, audio: audioLang) } } }) }` get error: Sending 'groupWrp' risks causing data races
0
0
87
2d
AVPlayerItem step(byCount:) callback or notification
Hello there, I need to move through video loaded in an AVPlayer one frame at a time back or forth. For that I tried to use AVPlayerItem's method step(byCount:) and it works just fine. However I need to know when stepping happened and as far as I observed it is not immediate using the method. If I check the currentTime() just after calling the method it's the same and if I do it slightly later (depending of the video itself) it shows the correct "jumped" time. To achieve my goal I tried subclassing AVPlayerItem and implement my own async method utilizing NotificationCenter and the timeJumpedNotification assuming it would deliver it as the time actually jumps but it's not the case. Here is my "stripped" and simplified version of the custom Player Item: import AVFoundation final class PlayerItem: AVPlayerItem { private var jumpCompletion: ( (CMTime) -> () )? override init(asset: AVAsset, automaticallyLoadedAssetKeys: [String]?) { super .init(asset: asset, automaticallyLoadedAssetKeys: automaticallyLoadedAssetKeys) NotificationCenter.default.addObserver(self, selector: #selector(timeDidChange(_:)), name: AVPlayerItem.timeJumpedNotification, object: self) } deinit { NotificationCenter.default.removeObserver(self, name: AVPlayerItem.timeJumpedNotification, object: self) jumpCompletion = nil } @discardableResult func step(by count: Int) async -> CMTime { await withCheckedContinuation { continuation in step(by: count) { time in continuation.resume(returning: time) } } } func step(by count: Int, completion: @escaping ( (CMTime) -> () )) { guard jumpCompletion == nil else { completion(currentTime()) return } jumpCompletion = completion step(byCount: count) } @objc private func timeDidChange(_ notification: Notification) { switch notification.name { case AVPlayerItem.timeJumpedNotification where notification.object as? AVPlayerItem [==](https://www.example.com/) self: jumpCompletion?(currentTime()) jumpCompletion = nil default: return } } } In short the notification never gets called thus the above is not working. I guess the key there is that in the docs about the timeJumpedNotification: is said: "A notification the system posts when a player item’s time changes discontinuously." so the step(byCount:) is not considered as discontinuous operation and doesn't trigger it. I'd be really helpful if somebody can help as I don't want to use seek(to:toleranceBefore:toleranceAfter:) mainly cause it's not accurate in terms of the exact next/previous frame as the video might have VFR and that causes repeating frames sometimes or even skipping one or another. Thanks a lot
2
0
134
5d
Swift6 race warning
I'm trying to fix some Swift6 warnings, this one seems too strict, I'm not sure how to fix it. The variable path is a String, which should be immutable, it's a local variable and never used again inside of the function, but still Swift6 complains about it being a race condition, passing it to the task What should I do here to fix the warning?
4
0
150
5d
How to debug or ensure single resume calls for continuations at compile time or with tools like Instruments?
When using the continuation API, we're required to call resume exactly once. While withCheckedContinuation helps catch runtime issues during debugging, I'm looking for ways to catch such errors at compile time or through tools like Instruments. Is there any tool or technique that can help enforce or detect this requirement more strictly than runtime checks? Or would creating custom abstractions around Continuation be the only option to ensure safety? Any suggestions or best practices are appreciated.
2
0
135
1w
StoreKit2 - Maintain property of purchased products
Hi everybody! I'm desperately looking for help as I'm stuck with a rather fundamental problem regarding StoreKit2 - and maybe Swift Concurrency in general: While renovating several freemium apps I'd like to move from local receipt validation with Receigen / OpenSSL to StoreKit2. These apps are using a dedicated "StoreManager" class which is encapsulating all App Store related operations like fetching products, performing purchases and listening on updates. For this purpose the StoreManager holds an array property with IDs of all purchased products, which is checked when a user invokes a premium function. This array can have various states during the app's life cycle: Immediately after app launch (before the receipt / entitlements are checked) the array is empty After checking the receipt the array holds all (locally registered) purchases Later on it might change if an "Ask to Buy" purchase was approved or a purchase was performed It is important that the array is instantly used in other (Objective-C) classes to reflect the "point in time" state of purchased products - basically acting like a cache: No async calls, completion handler, notification observer etc. When moving to StoreKit2 the same logic applies, but the relevant API calls are (of course) in asynchronous functions: Transaction.updates triggers Transaction.currentEntitlements, which needs to update the array property. But Xcode 16 is raising a strict error because of potential data races when accessing the instance variable from an asynchronous function / actor. What is the way to propagate IDs of purchased products app-wide without requiring every calling function as asynchronous? I'm sure I'm missing a general point with Swift Concurrency: Every example I found was working with call-backs / await, and although this talk of WWDC 2021 is addressing "protecting mutable states" I couldn't apply its outcomes to my problem. What am I missing?
3
0
223
1w
Help Needed: How to Make iOS Timer More Stable?
I’m currently developing an iOS metronome app using DispatchSourceTimer as the timer. The interval is set very small, around 50 milliseconds, and I’m using CFAbsoluteTimeGetCurrent to calculate the elapsed time to ensure the beat is played within a ±0.003-second margin. The problem is that once the app goes to the background, the timing becomes unstable—it slows down noticeably, then recovers after 1–2 seconds. When coming back to the foreground, it suddenly speeds up, and again, it takes 1–2 seconds to return to normal. It feels like the app is randomly “powering off” and then “overclocking.” It’s super frustrating. I’ve noticed that some metronome apps in the App Store have similar issues, but there’s one called “Professional Metronome” that’s rock solid with no such problems. What kind of magic are they using? Any experts out there who can help? Thanks in advance! P.S. I’ve already enabled background audio permissions. The professional metronome that has no issues: https://link.zhihu.com/?target=https%3A//apps.apple.com/cn/app/pro-metronome-%25E4%25B8%2593%25E4%25B8%259A%25E8%258A%2582%25E6%258B%258D%25E5%2599%25A8/id477960671
2
0
120
1w
Rewrite `UNNotificationServiceExtension` sub class into Swift 6 async await notation
I'm trying to rewrite a Swift code to Swift 6 language mode and am stuck with this problem. How do I safely pass the bestAttemptContent and contentHandler to the Task? This is from the UNNotificationServiceExtension subclass. final class NotificationService: UNNotificationServiceExtension { var contentHandler: ((UNNotificationContent) -> Void)? var bestAttemptContent: UNMutableNotificationContent? var customNotificationTask: Task<Void, Error>? override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { self.contentHandler = contentHandler bestAttemptContent = (request.content.mutableCopy() as? UNMutableNotificationContent) guard let bestAttemptContent = bestAttemptContent else { invokeContentHandler(with: request.content) return } do { let notificationModel = try PushNotificationUserInfo(data: request.content.userInfo) guard let templatedImageUrl = notificationModel.templatedImageUrlString, let imageUrl = imageUrl(from: templatedImageUrl) else { invokeContentHandler(with: bestAttemptContent) return } setupCustomNotificationTask( imageUrl: imageUrl, bestAttemptContent: bestAttemptContent, contentHandler: contentHandler ) } catch { invokeContentHandler(with: bestAttemptContent) } } // More code private func downloadImageTask( imageUrl: URL, bestAttemptContent: UNMutableNotificationContent, contentHandler: @escaping (UNNotificationContent) -> Void ) { self.customNotificationTask = Task { let (location, _) = try await URLSession.shared.download(from: imageUrl) let desiredLocation = URL(fileURLWithPath: "\(location.path)\(imageUrl.lastPathComponent)") try FileManager.default.moveItem(at: location, to: desiredLocation) let attachment = try UNNotificationAttachment(identifier: imageUrl.absoluteString, url: desiredLocation, options: nil) bestAttemptContent.attachments = [attachment] contentHandler(bestAttemptContent) } } } I tried using the MainActor.run {}, but it just moved the error to that run function. The UNNotificationRequest is not sendable, and I don't think I can make it so. Wrap the setupCustomNotification in a Task will move the errors to the didReceive method. It seems like the consuming keyword will help here, but it leads to a compilation error, even with the latest Xcode (16.2). Any pointers?
0
0
158
2w
WatchConnectivity Swift 6 - Incorrect actor executor assumption
I am trying to migrate a WatchConnectivity App to Swift6 and I found an Issue with my replyHandler callback for sendMessageData. I am wrapping sendMessageData in withCheckedThrowingContinuation, so that I can await the response of the reply. I then update a Main Actor ObservableObject that keeps track of the count of connections that have not replied yet, before returning the data using continuation.resume. ... @preconcurrency import WatchConnectivity actor ConnectivityManager: NSObject, WCSessionDelegate { private var session: WCSession = .default private let connectivityMetaInfoManager: ConnectivityMetaInfoManager ... private func sendMessageData(_ data: Data) async throws -> Data? { Logger.shared.debug("called on Thread \(Thread.current)") await connectivityMetaInfoManager.increaseOpenSendConnectionsCount() return try await withCheckedThrowingContinuation({ continuation in self.session.sendMessageData( data, replyHandler: { data in Task { await self.connectivityMetaInfoManager .decreaseOpenSendConnectionsCount() } continuation.resume(returning: data) }, errorHandler: { (error) in Task { await self.connectivityMetaInfoManager .decreaseOpenSendConnectionsCount() } continuation.resume(throwing: error) } ) }) } Calling sendMessageData somehow causing the app to crash and display the debug message: Incorrect actor executor assumption. The code runs on swift 5 with SWIFT_STRICT_CONCURRENCY = complete. However when I switch to swift 6 the code crashes. I rebuilt a simple version of the App. Adding bit by bit until I was able to cause the crash. See Broken App Awaiting sendMessageData and wrapping it in a task and adding the @Sendable attribute to continuation, solve the crash. See Fixed App But I do not understand why yet. Is this intended behaviour? Should the compiler warn you about this? Is it a WatchConnectivity issue? I initially posted on forums.swift.org, but was told to repost here.
3
0
341
2w
SwiftData and async functions
Hello, I recently published an app that uses Swift Data as its primary data storage. The app uses concurrency, background threads, async await, and BLE communication. Sadly, I see my app incurs many fringe crashes, involving EXC_BAD_ACCESS, KERN_INVALID_ADDRESS, EXC_BREAKPOINT, etc. I followed these guidelines: One ModelContainer that is stored as a global variable and used throughout. ModelContexts are created separately for each task, changes are saved manually, and models are not passed around. Threads with different ModelContexts might manipulate and/or read the same data simultaneously. I was under the impression this meets the usage requirements. I suspect perhaps the issue lies in my usage of contexts in a single await function, that might be paused and resumed on a different thread (although same execution path). Is that the case? If so, how should SwiftData be used in async scopes? Is there anything else particularly wrong in my approach?
1
0
260
2w
Strange crash when using .values from @Published publisher
Given the below code with Swift 6 language mode, Xcode 16.2 If running with iOS 18+: the app crashes due to _dispatch_assert_queue_fail If running with iOS 17 and below: there is a warning: warning: data race detected: @MainActor function at Swift6Playground/PublishedValuesView.swift:12 was not called on the main thread Could anyone please help explain what's wrong here? import SwiftUI import Combine @MainActor class PublishedValuesViewModel: ObservableObject { @Published var count = 0 @Published var content: String = "NA" private var cancellables: Set<AnyCancellable> = [] func start() async { let publisher = $count .map { String(describing: $0) } .removeDuplicates() for await value in publisher.values { content = value } } } struct PublishedValuesView: View { @ObservedObject var viewModel: PublishedValuesViewModel var body: some View { Text("Published Values: \(viewModel.content)") .task { await viewModel.start() } } }
2
0
222
4w
Using if statement in .overlay causes app to freeze when using withAnimation
I have an issue where a very specific configuration of .overlay, withAnimation, and a bindable state can freeze the app when the state changes. I've isolated the problematic source code into a sample project can be found here that demonstrates the issue: https://github.com/katagaki/IcyOverlay Steps to Reproduce To reproduce the issue, tap the 'Simulate Content Load' button. Once the progress bar has completed, a switch is toggled to hide the progress view, which causes the overlay to disappear, and the app to freeze. Any help and/or advice will be appreciated! Development Environment Xcode Version 16.2 (16C5032a), macOS 15.2(24C101) iOS SDK: 18.2 (22C146), Simulator: 18.2 (22C150)
1
0
243
Dec ’24
What are possible failures when using CLLocationUpdate.Updates AsyncSequence
Hello, I'm currently migrating my app location service to use the new CLLocationUpdate.Updates. I'm trying to understand what can fail in this AsyncSequence. Based on the previous CLError, I thought authorisation was one of them for example but it turns out that this is handled by the CLLocationUpdate where we can check different properties. So, is there a list of errors available somewhere? Thanks Axel, @alpennec
2
0
205
Dec ’24
Struggling with async/await: Fetching an image off the main thread
Hey everyone, I’m learning async/await and trying to fetch an image from a URL off the main thread to avoid overloading it, while updating the UI afterward. Before starting the fetch, I want to show a loading indicator (UI-related work). I’ve implemented this in two different ways using Task and Task.detached, and I have some doubts: Is using Task { @MainActor the better approach? I added @MainActor because, after await, the resumed execution might not return to the Task's original actor. Is this the right way to ensure UI updates are done safely? Does calling fetchImage() on @MainActor force it to run entirely on the main thread? I used an async data fetch function (not explicitly marked with any actor). If I were to use a completion handler instead, would the function run on the main thread? Is using Task.detached overkill here? I tried Task.detached to ensure the fetch runs on a non-main actor. However, it seems to involve unnecessary actor hopping since I still need to hop back to the main actor for UI updates. Is there any scenario where Task.detached would be a better fit? class ViewController : UIViewController{ override func viewDidLoad() { super.viewDidLoad() //MARK: First approch Task{@MainActor in showLoading() let image = try? await fetchImage() //Will the image fetch happen on main thread? updateImageView(image:image) hideLoading() } //MARK: 2nd approch Task{@MainActor in showLoading() let detachedTask = Task.detached{ try await self.fetchImage() } updateImageView(image:try? await detachedTask.value) hideLoading() } } func fetchImage() async throws -> UIImage { let url = URL(string: "https://via.placeholder.com/600x400.png?text=Example+Image")! //Async data function call let (data, response) = try await URLSession.shared.data(from: url) guard let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 else { throw URLError(.badServerResponse) } guard let image = UIImage(data: data) else { throw URLError(.cannotDecodeContentData) } return image } func showLoading(){ //Show Loader handling } func hideLoading(){ //Hides the loader } func updateImageView(image:UIImage?){ //Image view updated } }
5
0
583
2w
Core Data `context.performAndWait` in an actor
Hello. I am re-writing our way of storing data into Core Data in our app, so it can be done concurrently. The solution I opted for is to have a singleton actor that takes an API model, and maps it to a Core Data object and saves it. For example, to store an API order model, I have something like this: func store( order apiOrder: APIOrder, currentContext: NSManagedObjectContext? ) -&gt; NSManagedObjectID? { let context = currentContext ?? self.persistentContainer.newBackgroundContext() // … } In the arguments, there is a context you can pass, in case you need to create additional models and relate them to each other. I am not sure this is how you're supposed to do it, but it seemed to work. From what I've understood of Core Data and using multiple contexts, the appropriate way use them is with context.perform or context.performAndWait. However, since my storage helper is an actor, @globalActor actor Storage2 { … }, my storage's methods are actor-isolated. This gives me warnings / errors in Swift 6 when I try to pass the context for to another of my actor's methods. let context = … return context.performAndWait { // … if let apiBooking = apiOrder.booking { self.store(booking: apiBooking, context: context) /* causes warning: Sending 'context' risks causing data races; this is an error in the Swift 6 language mode 'self'-isolated 'context' is captured by a actor-isolated closure. actor-isolated uses in closure may race against later nonisolated uses Access can happen concurrently */ } // … } From what I understand this is because my methods are actor-isolated, but the closure of performAndWait does not execute in a thread safe environment. With all this, what are my options? I've extracted the store(departure:context:) into its own method to avoid duplicated code, but since I can't call it from within performAndWait I am not sure what to do. Can I ditch the performAndWait? Removing that makes the warning "go away", but I don't feel confident enough with Core Data to know the answer. I would love to get any feedback on this, hoping to learn!
0
0
258
Dec ’24
LocalAuthentication like Face ID crashes using swift 6 iOS 18.1
Hello, I have been implementing faceID authentication using LocalAuthentication, and I've noticed that if i use swift 5 this code compiles but when i change to swift 6 it gives me a crash saying this compile error: i have just created this project for this error purpose so this is my codebase: import LocalAuthentication import SwiftUI struct ContentView: View { @State private var isSuccess: Bool = false var body: some View { VStack { if isSuccess { Text("Succed") } else { Text("not succeed") } } .onAppear(perform: authenticate) } func authenticate() { let context = LAContext() var error: NSError? if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &amp;error) { let reason = "We need to your face to open the app" context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: reason) { sucexd, error in if sucexd { let success = sucexd Task { @MainActor [success] in isSuccess = success } } else { print(error?.localizedDescription as Any) } } } else { print(error as Any) } } } #Preview { ContentView() } also i have tried to not use the task block and also gives me the same error. i think could be something about the LAContext NSObject that is not yet adapted for swift 6 concurrency? also i tried to set to minimal but is the same error Im using xcode 16.1 (16B40) with M1 using MacOS Seqouia 15.0.1 Help.
2
1
352
Dec ’24
Why is flow control important?
One challenging aspect of Swift concurrency is flow control, aka backpressure. I was explaining this to someone today and thought it better to post that explanation here, for the benefit of all. If you have questions or comments, start a new thread in App & System Services > Processes & Concurrency and tag with Swift and Concurrency. Share and Enjoy — Quinn “The Eskimo!” @ Developer Technical Support @ Apple let myEmail = "eskimo" + "1" + "@" + "apple.com" Why is flow control important? In Swift concurrency you often want to model data flows using AsyncSequence. However, that’s not without its challenges. A key issue is flow control, aka backpressure. Imagine you have a network connection with a requests property that returns an AsyncSequence of Request values. The core of your networking code might be a loop like this: func processRequests(connection: Connection) async throws { for try await request in connection.requests { let response = responseForRequest(request) try await connection.reply(with: response) } } Flow control is important in both the inbound and outbound cases. Let’s start with the inbound case. If the remote peer is generating requests very quickly, the network is fast, and responseForRequest(_:) is slow, it’s easy to fall foul of unbounded memory growth. For example, if you use AsyncStream to implement the requests property, its default buffering policy is .unbounded. So the code receiving requests from the connection will continue to receive them, buffering them in the async stream, without any bound. In the worst case scenario that might run your process out of memory. In a more typical scenario it might result in a huge memory spike. The outbound case is similar. Imagine that the remote peer keeps sending requests but stops receiving them. If the reply(with:) method isn’t implemented correctly, this might also result in unbounded memory growth. The solution to this problem is flow control. This flow control operates independently on the send and receive side: On the send side, the code sending responses should notice that the network connection has asserted flow control and stop sending responses until that flow control lifts. In an async method, like the reply(with:) example shown above, it can simply not return until the network connection has space to accept the reply. On the receive side, the code receiving requests from the connection should monitor how many are buffered. If that gets too big, it should stop receiving. That causes the requests to pile up in the connection itself. If the network connection implements flow control properly [1], this will propagate to the remote peer, which should stop generating requests. [1] TCP and QUIC both implement flow control. Use them! If you’re tempted to implement your own protocol directly on top of UDP, consider how it should handle flow control. Flow control and Network framework Network framework has built-in support for flow control. On the send side, it uses a ‘push’ model. When you call send(content:contentContext:isComplete:completion:) the connection buffers the message. However, it only calls the completion handler when it’s passed that message to the network for transmission [2]. If you send a message and don’t receive this completion callback, it’s time to stop sending more messages. On the receive side, Network framework uses a ‘pull’ model. The receiver calls a receive method, like receiveMessage(completion:), which calls a completion handler when there’s a message available. If you’ve already buffered too many messages, just stop calling this receive method. These techniques are readily adaptable to Swift concurrency using Swift’s CheckedContinuation type. That works for both send and receive, but there’s a wrinkle. If you want to model receive as an AsyncSequence, you can’t use AsyncStream. That’s because AsyncStream doesn’t support flow control. So, you’ll need to come up with your own AsyncSequence implementation [3]. [2] Note that this doesn’t mean that the data has made it to the remote peer, or has even been sent on the wire. Rather, it says that Network framework has successfully passed the data to the transport protocol implementation, which is then responsible for getting it to the remote peer. [3] There’s been a lot of discussion on Swift Evolution about providing such an implementation but none of that has come to fruition yet. Specifically: The Swift Async Algorithms package provides AsyncChannel, but my understanding is that this is not yet ready for prime time. I believe that the SwiftNIO folks have their own infrastructure for this. They’re driving this effort to build such support into Swift Async Algorithms. Avoid the need for flow control In some cases you can change your design to avoid the need for control. Imagine that your UI needs to show the state of a remote button. The network connection sends you a message every time the button is depressed or released. However, your UI only cares about the current state. If you forward every messages from the network to your UI, you have to worried about flow control. To eliminate that worry: Have your networking code translate the message to reflect the current state. Use AsyncStream with a buffering policy of .bufferingNewest(1). That way there’s only ever one value in the stream and, if the UI code is slow for some reason, while it might miss some transitions, it always knows about the latest state. 2024-12-13 Added a link to the MultiProducerSingleConsumerChannel PR. 2024-12-10 First posted.
0
0
387
Dec ’24
SwiftData Crash: Incorrect actor executor assumption.
I have this actor actor ConcurrentDatabase: ModelActor { nonisolated let modelExecutor: any ModelExecutor nonisolated let modelContainer: ModelContainer init(modelContainer: ModelContainer) { self.modelExecutor = DefaultSerialModelExecutor(modelContext: ModelContext(modelContainer)) self.modelContainer = modelContainer } /// Save pending changes in the model context. private func save() { if self.modelContext.hasChanges { do { try self.modelContext.save() } catch { ... } } } } I am getting a runtime crash on: try self.modelContext.save() when trying to insert something into the database and save Thread 1: Fatal error: Incorrect actor executor assumption; Expected same executor as MainActor. Can anyone explain why this is happening?
2
0
313
Dec ’24
Checking authorization status of AVCaptureDevice or CLLocation Manager gives runtime warnings in iOS 18
I have the following code in my ObservableObject class and recently XCode started giving purple coloured runtime issues with it (probably in iOS 18): Issue 1: Performing I/O on the main thread can cause slow launches. Issue 2: Interprocess communication on the main thread can cause non-deterministic delays. Issue 3: Interprocess communication on the main thread can cause non-deterministic delays. Here is the code: @Published var cameraAuthorization:AVAuthorizationStatus @Published var micAuthorization:AVAuthorizationStatus @Published var photoLibAuthorization:PHAuthorizationStatus @Published var locationAuthorization:CLAuthorizationStatus var locationManager:CLLocationManager override init() { // Issue 1 (Performing I/O on the main thread can cause slow launches.) cameraAuthorization = AVCaptureDevice.authorizationStatus(for: AVMediaType.video) micAuthorization = AVCaptureDevice.authorizationStatus(for: AVMediaType.audio) photoLibAuthorization = PHPhotoLibrary.authorizationStatus(for: .addOnly) //Issue 1: Performing I/O on the main thread can cause slow launches. locationManager = CLLocationManager() locationAuthorization = locationManager.authorizationStatus super.init() //Issue 2: Interprocess communication on the main thread can cause non-deterministic delays. locationManager.delegate = self } And also in route Change notification handler of AVAudioSession.routeChangeNotification, //Issue 3: Hangs - Interprocess communication on the main thread can cause non-deterministic delays. let categoryPlayback = (AVAudioSession.sharedInstance().category == .playback) I wonder how checking authorisation status can give these issues? What is the fix here?
1
0
319
Dec ’24