Discuss Swift.

Swift Documentation

Post

Replies

Boosts

Views

Activity

Model instance invalidated, backing data could no longer be found in the store
I have been recently getting the following error seemingly randomly, when an event handler of a SwiftUI view accesses a relationship of a SwiftData model the view holds a reference to. I haven't yet found a reliable way of reproducing it: SwiftData/BackingData.swift:866: Fatal error: This model instance was invalidated because its backing data could no longer be found the store. PersistentIdentifier(id: SwiftData.PersistentIdentifier.ID(url: COREDATA_ID_URL), implementation: SwiftData.PersistentIdentifierImplementation) What could cause this error? Could you suggest me a workaround?
1
0
61
13h
SwiftData Query filter().first crashed in iOS18.2
Hi There, I have a iOS App which has been published and purely managing data by SwiftData. I use following simple codes everywhere in Views: ... @Query var items: [Item] .... if let firstItem = items.first( where: {...}) { ... Then I encountered crash at Query that _items.wrapperdValue has some errors. Then I tried to split first(where...) into ordinary way: let filteredItems = items.filter(...) if let firstItem = filteredItems.first { ... It runs OK. Is it a bug in SwiftData in 18.2 or I missed some steps to facilitate SwiftData macros?
0
0
45
18h
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
84
1d
Can't use Link in .systemLarge widget
I just added a .systemLarge widget to my app, but I can't get Links to work. I want the user to be able to tap one of the four rows in my widget - like the EmojiRangers example - but I can't get it to work. I watched a Developer video from WWDC20: https://developer.apple.com/videos/play/wwdc2020/10036?time=223 The guy, Izzy, 'simply' embeds an HStack in a Link, and hey presto! It all works. But that doesn't happen for me. There's clearly some code in the background that runs. I already have .widgetURL working for .systemSmall and .systemMedium widgets, and I don't need to use Links on those two types. Those work by sending a URL to .onOpenURL { incomingURL in ... All good there, no issues. I've wrapped each row in the large widget in a Link with the URL of something like myappurlscheme://widgetTapped/widgetId (it's the same url as that used in the small and medium widgets). I build & run. I tap a row. It doesn't act as though a row is tappable (it doesn't go slightly transparent), and just opens the app without hitting .onOpenURL or anything else. Nothing in my scene delegate is triggered. Is there a specific delegate method that gets called? Do I need to set up some awful intents? I'm not using any sort of NavigationStack here; that model doesn't fit my app. Any ideas? Thanks.
1
0
104
3d
AppleScriptLauncher Menu App
I'm primarily an AppleScript writer and only a novice programmer, using ChatGPT to help me with the legwork. It has helped me to write a functioning app that builds a menu structure based on the scripts I have in the Scripts directory used in the script menu and then runs the applescripts. When I distribute the app to my desktop and run it, the scripts that access other apps, like InDesign will cause it to launch, but not actually do anything. I included the ids for each app in the entitlements dictionary and have given the app full disk access in system settings, but it's not functioning as I'd expect. I know there are apps like Alfred that allow you to run scripts from a keystroke, but I'm building this for others I work with so they can also access info about each script, what it does, and how to use it from the menu, as well as key commands to run them. Not sure what else to say, but if this sounds like a simple fix to anyone, please let me know.
0
0
126
4d
Database Download Record Fetch Fails in MacOS 15.2
A program I wrote in Swift that uploads and downloads to a private database in iCloud is failing for downloads since the the 15.2 update. It still works for uploads. I.e., I can download uploads made from the program under 15.2 on another computer running the same program under 15.1 The Fetch operation does not return an error, but the returnRecord is empty! I do get the error below after the fact of the failure, don't know if it's related. "ViewBridge to RemoteViewService Terminated: Error Domain=com.apple.ViewBridge Code=18 "(null)" UserInfo={com.apple.ViewBridge.error.hint=this process disconnected remote view controller -- benign unless unexpected, com.apple.ViewBridge.error.description=NSViewBridgeErrorCanceled}" To be clear, I assume I do have access to the database since it works for upload under 15.2, as well as upload and download under 15.1, and from a very similar program on my iPhone (which I haven't updated yet!) Questions? Comments? Thanks!
0
0
149
5d
Passing compatible primitive types as reference in cpp-swift interop
I have an xcode project which has both cpp and swift code. In one of my usecase I am passing primitive type variables from swift to cpp by reference( primitives types list here as per the new cpp-swift interop documentation) swift code: // primitive check code:Bool var x : Bool = true // When we are passing a variable as a Reference, we need to use explicitly use'&' student.PassBoolAsReferenceType (&x) // interop call to cpp code print (x) Cpp code: void Student::PassBoolAsReferenceType(bool &pValue) noexcept { std::cout << pValue << std::endl; pValue = false; } The above code fails during compilation with no clear error message "Command SwiftCompile failed with a nonzero exit code" However, all the other primitive types that I tested worked for the above code like Int, Float, Double etc. Only the Bool interop fails. Can someone explain why is it not possible for bool? I m using the new interop introduced in swift 5.9.
1
0
134
5d
String functions problems on iOS18
On iOS 18 some string functions return incorrect values in some cases. Found problems on replacingOccurrences() and split() functions, but there may be others. In the results of these functions in some cases a character is left in the result string when it shouldn't. This did not happen on iOS17 and older versions. I created a very simple Test Project to reproduce the problem. If I run these tests on iOS17 or older the tests succeed. If I run these tests on iOS18 the tests fail. test_TestStr1() function shows a problem in replacingOccurrences() directly using strings. test_TestStr2() function shows a problem in split() that seems to happen only when bridging from NSString to String. import XCTest final class TestStrings18Tests: XCTestCase { override func setUpWithError() throws { // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDownWithError() throws { // Put teardown code here. This method is called after the invocation of each test method in the class. } func test_TestStr1() { let str1 = "_%\u{7}1\u{7}_"; let str2 = "%\u{7}1\u{7}"; let str3 = "X"; let str4 = str1.replacingOccurrences(of: str2, with: str3); //This should be true XCTAssertTrue(str4 == "_X_"); } func test_TestStr2() { let s1 = "TVAR(6)\u{11}201\"Ã\"\u{11}201\"A\""; let s2 = s1.components(separatedBy: "\u{11}201"); let t1 = NSString("TVAR(6)\u{11}201\"Ã\"\u{11}201\"A\"") as String; let t2 = t1.components(separatedBy: "\u{11}201"); XCTAssertTrue(s2.count == t2.count); let c = s2.count //This should be True XCTAssertTrue(s2[0] == t2[0]); } }
3
0
175
5d
How to dismiss an ImmersiveSpace when the main window closes?
I noticed that when I enter the fully immersive view and then click the X button below the window, the immersive space remains active, and the only way to dismiss it is to click the digital crown. On other apps (Disney+ for example), closing out of the main window while in immersive mode also closes out the immersive space. I tried applying an onDisappear modifier to the the Modules view with a dismissImmersiveSpace, but that doesn't appear to do anything. Any help would be appreciated.
1
0
118
5d
Musickit Media player missing output device selection
Hi All, I am working on a DJ playout app (MACOS). The app has a few AVAudioPlayerNode's combined with the ApplicationMusicPlayer from Musickit. I can route the output of the AVaudioPlayer to a hardware device so that the audio files are directed to their own dedicated output on my Mac. The ApplicationMusicPlayer is following the default output and this is pretty annoying. Has anyone found a solution to chain the ApplicationMusicPlayer and get it set to a output device? Thanks Pancras
1
0
100
6d
The UWB performance of iOS18 is different from that of iOS17
Hello, dear engineer: The UWB Accessory used by my APP has inconsistent code callbacks on iOS17 and iOS18. I have connected multiple UWB Accessory by Accessory Single Configuration Data (UUID: 95e8d9d5-d8ef-4721-9a4e-807375f53328) in the APP. In iOS17.5.1, the unconnected Accessory calls the func session in the NiSessionDelegate (_ session: NISession, didRemove nearbyObjects: [NINearbyObject], "reason: NINearbyObject RemovalReason)," reason is the timeout. iOS18.0.1 does not call didRemove and fails to connect automatically after 10 minutes on the disconnected Accessory. iOS18.2 does not call didRemove. After 10 minutes, when the Accessory is not connected, it automatically connects and starts ranging. Therefore, I would like to ask what is updated in iOS18 UWB? Is there a document for reference, or can you provide the callback performance of each iOS version for UWB? The code is as follows: niConfiguration = try NINearbyAccessoryConfiguration(data: Data(AccessoryUwbConfigData)) uwbSession.run(niConfiguration)
0
0
115
6d
Best way to measure days between dates
Hey team I'm facing an issue where startDate is 1 January 2025 and endDate is 31 March 2025 between this 2 dates is 90 days, but on my code is being taken as 89 days I've seen the math of the code excludes the first partial day (from midnight to 06:00) on 2025-01-01, which results in 89 full days instead of 90 days. startDate: 2025-01-01 06:00:00 +0000 endDate: 2025-03-31 06:00:00 +0000 this is my function func daysBetweenDates() -> Int? { guard let selectedStartDate = selectedStartDate?.date else { return nil } guard let selectedEndDate = selectedEndDate?.date else { return 0 } let calendar = Calendar.current let dateComponents = calendar.dateComponents([.day], from: selectedStartDate, to: selectedEndDate) return dateComponents.day } what I've tried is reset the hours to 0 so it can take the full day and return 90 days like this func daysBetweenDates() -> Int? { guard let selectedStartDate = selectedStartDate?.date else { return nil } guard let selectedEndDate = selectedEndDate?.date else { return 0 } var calendar = Calendar(identifier: .gregorian) calendar.timeZone = TimeZone(secondsFromGMT: 0) ?? .current let cleanMidNightStartDate = calendar.startOfDay(for: selectedStartDate) let cleanMidNightEndDate = calendar.startOfDay(for: selectedEndDate.addingTimeInterval(24 * 60 * 60)) let dateComponents = calendar.dateComponents([.day], from: cleanMidNightStartDate, to: cleanMidNightEndDate) let daysCount = dateComponents.day ?? 0 return daysCount } this worked for that date specifically but when I tried to change the date for example startDate: 18 December 2024. endDate: 18 March 2025. between those dates we have 90 days but this function now reads 91. what I'm looking is a cleaver solution for this problem so I can have the best posible quality code, thanks in advance!
1
0
143
1w
UIViewRepresentable is not working
I have been trying to integrate a UIKit view into SwiftUI, specifically a WKWebView. However, I keep encountering a does not conform to protocol error. Here's my code: import SwiftUI import WebKit struct SimpleWebView: View { var body: some View { WebViewContainerRepresentable() .edgesIgnoringSafeArea(.all) } } struct WebViewContainerRepresentable: UIViewRepresentable { typealias UIViewType = WKWebView func makeUIView(context: Context) -> WKWebView { let webView = WKWebView() if let url = Bundle.main.url(forResource: "index", withExtension: "html") { webView.loadFileURL(url, allowingReadAccessTo: url.deletingLastPathComponent()) } return webView } func updateUIView(_ uiView: WKWebView, context: Context) { // Updates not required for this use case } } I tried this with other views as well, and it turns out this is not WKWebView-specific. The minimum deployment version is iOS 15. Any help would be much appreciated. Let me know if I need to add any more information.
1
0
147
1w
Get CloudKit records created by specific user
I've been searching all over the web trying to find the proper way to get all records created by a specific user in CloudKit. I am able to get the correct id using: guard let userRecordID = try? await container.userRecordID() else { return } I can see that the id returned is associated with records in my CloudKit dashboard. So I would expect that the following would get those records: let predicate = NSPredicate(format: "%K == %@", #keyPath(CKRecord.creatorUserRecordID), userRecordID) let query = CKQuery(recordType: "CKUser", predicate: predicate) But instead when I use that query it returns nothing. It is successful but with nothing returned... Any ideas why this would be happening? P.S. I have also tried constructing the predicate using the reference, but I get the same result - success with no results. P.S.2 Also worth mentioning that I am trying to get the results from the public database and I have set my CKContainer to the correct container id.
5
0
229
1w
Decryption failure - Migrated from Objective-C to Swift (AES256 Decryption failure in swift language)
Decrypting Data to String Conversion failure Development environment: Xcode 15.4, macOS 14.7 Run-time configuration: iOS 15.8.1 & 16.0.1 DESCRIPTION OF PROBLEM We were using objective C implementation of CCCrypt(see below) in our app earlier which we migrated to swift implementation recently. We convert the byte array that CCCrypt returns into Data, and data to string to read the decrypted value. It works perfectly fine in Objective C, whereas with new swift implementation this conversion is failing, it looks like CCCrypt is returning byte array with few non UTF8 characters and that conversion is failing in swift since Objective C is more tolerant with this conversion and converts the byte array to Data and then to string even though there are few imperfect UTF characters in the array. Objective C CCCryptorStatus CCCrypt( CCOperation op, /* kCCEncrypt, etc. / CCAlgorithm alg, / kCCAlgorithmAES128, etc. / CCOptions options, / kCCOptionPKCS7Padding, etc. */ const void *key, size_t keyLength, const void iv, / optional initialization vector */ const void dataIn, / optional per op and alg */ size_t dataInLength, void dataOut, / data RETURNED here */ size_t dataOutAvailable, size_t *dataOutMoved) API_AVAILABLE(macos(10.4), ios(2.0)); Swift Code CCCrypt(_ op: CCOperation, _ alg: CCAlgorithm, _ options: CCOptions, _ key: UnsafeRawPointer!, _ keyLength: Int, _ iv: UnsafeRawPointer!, _ dataIn: UnsafeRawPointer!, _ dataInLength: Int, _ dataOut: UnsafeMutableRawPointer!, _ dataOutAvailable: Int, _ dataOutMoved: UnsafeMutablePointer!) -> CCCryptorStatus Data to String Conversion String(data: decryptedData, encoding: .utf8) STEPS TO REPRODUCE Able to reproduce on below devices iPhone - 7 OS Version 15.8.1 iPhone 14- Pro OS Version 16.0.2 iPhone 15 iOS 18.0.1 **Decryption method return "Data" and converting into string using ".utf8" but String conversion is failing on above devices and some other devices as well. Decryption failure not occurring always. ** Below code used for String conversion String(data: decryptedData, encoding: .utf8)
0
0
90
1w
libswiftNetwork.dylib randomly crashed on iOS 16
My application crash on iOS 16 randomly, stack trace like this: libswiftCore.dylib __swift_release_dealloc + 32 libswiftNetwork.dylib outlined consume of (@escaping @callee_guaranteed (@in_guaranteed Network.NWConnection.State) -> ())? + 52 libswiftNetwork.dylib outlined consume of (@escaping @callee_guaranteed (@in_guaranteed Network.NWConnection.State) -> ())? + 52 libswiftCore.dylib __swift_release_dealloc + 56 libsystem_blocks.dylib __call_dispose_helpers_excp + 48 libsystem_blocks.dylib __Block_release + 252 libsystem_blocks.dylib bool HelperBase::disposeCapture<(HelperBase::BlockCaptureKind)4>(unsigned int, unsigned char*) + 68 libsystem_blocks.dylib HelperBase::destroyBlock(Block_layout*, bool, unsigned char*) + 180 libsystem_blocks.dylib __call_dispose_helpers_excp + 72 libsystem_blocks.dylib __Block_release + 252 libdispatch.dylib ___destroy_helper_block_8_32c35typeinfo name for dispatch_block_private_data_s + 96 libsystem_blocks.dylib __call_dispose_helpers_excp + 48 libsystem_blocks.dylib __Block_release + 252 libdispatch.dylib __dispatch_client_callout + 20 libdispatch.dylib __dispatch_root_queue_drain + 684 libdispatch.dylib __dispatch_worker_thread2 + 164 libsystem_pthread.dylib __pthread_wqthread + 228 From buly(a tool to report crash) we notice that this crash only happens on iOS 16
1
0
104
1w
array
I'm using xcode 16.1 withSwift. I want to know how to call a function passing in an array. Also I need to know how to declare the function receiving the array. I currently have: func myfunc(costa: [Double]) { } I call it like this: myfunc(costa:[ ]) It's an array of Doubles. I don't get any errors but the array is always empty. Please help. Thank you.
3
0
121
1w
Trying to understand Swift-C++ interopability
Hi, I'm struggling to understand using Swift-C++ in the same project. I have an existing code-base that makes heavy use of Swift-Objective-C interoperability. We make use of swift classes in our project. When I enable swift-objective c interoperability I am running into numerous build errors in the generated bridging header. I'm trying to understand why these errors exist and what to do to get around them. I have a project that I've set up with some test code, and I'm running into an error here: public class Foo { let name: String public init(name: String) { self.name = name } } public class Bar { let name: String public init(name : String) { self.name = name; } public func getFoo() -> Foo { return Foo(name: self.name); } } In the header file: Unknown type name 'Foo' SWIFT_INLINE_THUNK Foo getFoo() SWIFT_SYMBOL("s:13ForestBuilder3BarC6getFooAA0E0CyF"); This error goes away if I use structs, but for the purposes of porting my codebase, I'd prefer to use classes. Do classes not play nice here? Or am I misunderstanding something. Thanks.
0
0
123
1w