Discuss Swift.

Swift Documentation

Post

Replies

Boosts

Views

Activity

SwiftData error 134020 - "The model configuration used to open the store is incompatible with the one that was used to create the store."
Hi all, I have tried everything (that i'm aware of) but i cannot seem to get around this error. My app is setup using only SwiftData and is basically a custom version of the apps shown in SwiftData docs. I have done the following to try to debug: Deleted app from device Clean and re-build Delete derived data and rebuild I have tried reverting changes made to the @Models i have define Every combination of the above steps + rebuilding Im at a loss. No clue how to resolve this. Some weird observations. This error only occurs after the first context.insert call. The first is successful and data is properly persisted across app launches. All subsequent attempts to insert result in the following error: Error Domain=NSCocoaErrorDomain Code=134020 "The model configuration used to open the store is incompatible with the one that was used to create the store." UserInfo={NSAffectedObjectsErrorKey=<NSManagedObject: 0x2824004b0> (entity: Track; id: 0x2807a7de0 <x-coredata:///Track/tB9B77486-8F60-4F63-848D-D1C5CC67BA526>; data: { createdAt = "2023-07-02 23:45:45 +0000"; name = Test; })}
5
3
1.6k
Jul ’23
XCUIElement's Print Statement Not Including Nested Button
Example Image: Expected Behavior: When an XCUIElement is rendered from a screen with (Initial Conditions): An ImageView with.. isUserInteractionEnabled = YES… IsAccessibilityElement = YES… A nested button… isUserInteractionEnabled = YES… IsAccessibilityElement = YES… Assigned to the ImageViews accessibility elements array XCUIElement’s print statement includes the nested button Current Behavior: When an XCUIElement is rendered from a screen with: (above Initial Conditions) XCUIElement’s print statement only include the ImageView Attempted Fixes: Combinations of the Initial Conditions: Attempted all combinations of Initial Condition variable values. (ie: myImageView.accessibilityElements = [imageView, nestedButton] myImageView.accessibilityElements = [nestedButton] isUserInteractionEnabled = YES/NO [for both] IsAccessibilityElement = YES/NO [for both] etc…) Debug Print: Image View with No Descendants - Image, 0x7fa875d23e80, {{172.7, 292.7}, {45.0, 41.7}}, label: 'demo image' po element.images and po element.buttons - Find: Descendants matching type Image Output: { Image, 0x7fa876e14e70, {{-8.0, 99.0}, {136.7, 109.3}} Image, 0x7fa876e14f80, {{-8.0, 741.7}, {136.7, 102.3}} Image, 0x7fa876e13da0, {{269.7, 737.0}, {136.3, 123.0}} Image, 0x7fa876e1a060, {{172.7, 292.7}, {45.0, 41.7}}, label: 'demo image' } Output: { Button, 0x7fa875c12740, {{0.0, 47.0}, {68.0, 44.0}}, label: 'myApp UIKit' Button, 0x7fa875c24f00, {{338.0, 47.0}, {44.0, 44.0}}, identifier: 'Settings Button', label: 'Settings' Button, 0x7fa875c2c800, {{175.0, 533.0}, {40.0, 40.0}} Button, 0x7fa875c2cf30, {{183.0, 541.0}, {24.0, 24.0}} Button, 0x7fa875c2fa20, {{40.0, 659.3}, {153.0, 44.0}}, label: 'Left' Button, 0x7fa875c30cd0, {{197.0, 659.3}, {153.0, 44.0}}, label: 'Right' } Comparing the coordinates of the parent image view and the nested button, the button isn't here. The 24x24 button that appears comes from another view on the same screen, noting the ample y coordinate from the parent image view. Request: Request that Apple, in the spirit of XCUI framework being to be near to human experience include this common design case
1
1
587
Jul ’23
[WindowHosting] UIScene property of UINSSceneViewController was accessed before it was set. What does this mean?
Getting this error several times when presenting a modal window over my splitview window when running it on my Mac using Swift/Mac Catalyst in XCode 14.2. When I click the Cancel button in the window then I get Scene destruction request failed with error: (null) right after an unwind segue. 2023-07-04 16:50:45.488538-0500 Recipes[27836:1295134] [WindowHosting] UIScene property of UINSSceneViewController was accessed before it was set. 2023-07-04 16:50:45.488972-0500 Recipes[27836:1295134] [WindowHosting] UIScene property of UINSSceneViewController was accessed before it was set. 2023-07-04 16:50:45.496702-0500 Recipes[27836:1295134] [WindowHosting] UIScene property of UINSSceneViewController was accessed before it was set. 2023-07-04 16:50:45.496800-0500 Recipes[27836:1295134] [WindowHosting] UIScene property of UINSSceneViewController was accessed before it was set. 2023-07-04 16:50:45.994147-0500 Recipes[27836:1295134] Unbalanced calls to begin/end appearance transitions for <UINavigationController: 0x7f7fdf068a00>. bleep 2023-07-04 16:51:00.655233-0500 Recipes[27836:1297298] Scene destruction request failed with error: (null) I don't quite understand what all all this means. (The "bleep" was a debugging print code I put in the unwind segue). I'm working through Apple's Mac Catalyst tutorial but it seems to be riddled with bugs and coding issues, even in the final part of the completed app which I dowmloaded and ran. I don't see these problems on IPad simulator. I don't know if it's because Catalyst has problems itself or there's something else going on that I can fix myself. Any insight into these errors would be very much appreciated! PS: The app seems to run ok on Mac without crashing despite the muliple issues
3
2
1.1k
Jul ’23
Xcode 15b3 Swift 5.9 C++ Interop with Network Extension
Just a quick observation. I find that the NSNotification.Name NEVPNStatusDidChange is not visible when the Swift Compiler setting: C++ and Objective-C Interoperability is set to C++/Objective-C++. Simply switching between C/Objective-C and C++/Objective-C++, a successfully building app is no longer able to build with error: Type 'NSNotification.Name?' has no member 'NEVPNStatusDidChange'. The Swift code being used is: NotificationCenter.default.addObserver(self, selector: #selector(self.updateNetworkStatus(_:)), name: .NEVPNStatusDidChange, object: nil)
4
0
831
Jul ’23
Querying HealthKit for Manually-Entered Medication
I'm trying to query HealthKit for all of users medications, including prescribed medications and user-entered medications. Using a HKSampleQuery with type HKClinicalTypeIdentifierMedicationRecord, I'm able to fetch medications that have been prescribed by a healthcare provider (eg medications associated with clinical FHIR records): let type = HKClinicalType(.medicationRecord) let predicate = HKQuery.predicateForClinicalRecords(withFHIRResourceType: .medicationStatement) let query = HKSampleQuery(sampleType: type, predicate: predicate, limit: kRecordLimit, sortDescriptors: nil) { q, samples, error in // this returns only -clinical- records // it doesnt include manually entered meds } However, medications which I have manually entered into the Health app with a user-defined schedule and dosing do NOT appear in the results of this query. is it possible to fetch medications which have been manually entered by the user?
3
1
999
Jul ’23
Cannot convert value of type 'int' to expected argument type 'string'?
Hello everyone. I was a building a test app when I encountered this error: I'm new to indices and am a bit confused by them. Can someone please explain the error to me and show me a possible solution to it? Many thanks! Here is my code: import SwiftUI struct GameView: View { @StateObject var viewModel = GameViewModel() var body: some View { ZStack { GameColor.main.ignoresSafeArea() VStack { Text(viewModel.progressText) .padding() Spacer() Text(viewModel.questionText) .font(.title) .multilineTextAlignment(.center) .padding() Spacer() Spacer() HStack { ForEach(0..<viewModel.answerIndices.count, id: \.self) { index in AnswerButton(text: viewModel.answerIndices[index]) { // ForEach(viewModel.answerIndices) { index in // AnswerButton(text: viewModel.answerText(for: index)) { viewModel.makeSelectionForCurrentQuestion(at: index) } .background(viewModel.colorForButton(at: index)) .disabled(viewModel.selectionWasMade) } } if viewModel.selectionWasMade { Button(action: viewModel.advanceGameState, label: { BottomText(str: "Next") }) } }.padding(.bottom) } .navigationBarHidden(true) .background(resultsNavigationLink) } private var resultsNavigationLink: some View { NavigationLink( destination: ResultsView(viewModel: ResultsViewModel(selectionCount: viewModel.selectionCount, gameStartTime: viewModel.gameStartTime, gameEndTime: Date())), isActive: .constant(viewModel.gameIsOver), label: { EmptyView() }) } } struct AnswerButton: View { let text: String let onClick: () -> Void var body: some View { Button(action: { onClick() }) { Text(text) } .padding() .border(Color.blue, width: 4) } } struct ContentView_Previews: PreviewProvider { static var previews: some View { NavigationView { GameView() } } } (Above is the view; this is the model: import SwiftUI class GameViewModel: ObservableObject { @Published var game = Game() var questionText: String { game.currentQuestion.questionText } var answerIndices: Range<Int> { game.currentQuestion.possibleAnswers.indices } var correctAnswerIndex: Int { game.currentQuestion.correctAnswerIndex } var progressText: String { "Question \(game.currentQuestionIndex + 1) / \(game.questionCount)" } var selectionWasMade: Bool { game.selections[game.currentQuestion] != nil } var selectionCount: (Int, Int) { game.selectionCount } var gameIsOver: Bool { game.gameIsOver } var gameStartTime: Date { game.startTime } func answerText(for index: Int) -> String { game.currentQuestion.possibleAnswers[index] } func advanceGameState() { game.advanceGameState() } func makeSelectionForCurrentQuestion(at index: Int) { game.makeSelection(at: index) } func colorForButton(at buttonIndex: Int) -> Color { guard let selectedIndex = game.selections[game.currentQuestion], selectedIndex == buttonIndex else { return .clear } if selectedIndex == correctAnswerIndex { return .green } else { return .red } } } Thanks for the help in advance!
5
0
2.2k
Jul ’23
FirstTimeDebugging - compile warning
Dear community, I'm reading "Develop in Swift Fundamentals", and on page 89 it asks us to open a file from the downloaded file (page 9 - Download Student Materials link). I was running the last part of the exercise of page 89 and it seems I got stuck when trying to remove the last compile warning message: "1. Condition always evaluates to false" "Will never be executed" Please take a look at the screenshot, where you can see the whole code and context. I have tried to add a few breakpoints (rows 10 to 12) in order to see if they would get ignored but it looks like it's still there. Any idea how to remove / get rid of this compile warning message? Thanks, Rodrigo
4
0
735
Jul ’23
I want to close my app after a while in background mode
I am sorry for my poor English. I know that a callback of timer is not called in background mode. I know that I should add capabilities, permissions and keys into the Info file for doing something in background mode. But I do not need any complicated task in background mode, just need to terminate my app automatically after 30 minutes in background mode. Is there a simple way for that purpose?
4
0
1.2k
Jul ’23
Peculiar EXC_BAD_ACCESS, involving a Task
I had to update a simple piece of code, so it could be delayed by a few ms in some cases. This is how I tried to achieve that, by using a Task: class SomeClass { private var availableStuff : Set&lt;Stuff&gt; = [] func updateStuff(lookingFor prop: SomeProp, updatedThing: String, waiting: Duration = .zero) { Task { if waiting != .zero { try await Task.sleep(for: waiting) } if var stuff = availableStuff.first(where: { $0.prop == prop }) { stuff.thing = updatedThing // print(availableStuff) self.availableStuff.remove(stuff) self.availableStuff.insert(stuff) // BAD ACCESS here } } } } It did work before implementing the delay, but now it would crash at the insert statement (sometimes at remove). Naively, I put a print statement beforehand and to my surprise, this kept the crash from occurring at all! I switched on Address Sanitizer, now it doesn't crash, even w/o the print statement. Am I using the Task wrong, somehow? How can I further diagnose this, so it doesn't happen later in production? Or should I just leave the print in and hope for the best? Thanks!
1
0
935
Jul ’23
Simple Crash detection
I am trying to get simple crash detection working. Ten years ago was that no problem with Obj-C thankss to the UncaughtExceptionHandler. But Swift needs more work and I am not sure I am on the right path after I the TheEskimos posts. I tried the following implementation, based on other approaches and comments. To my surprise it seems not to get called. Any idea what I am missing or doing wrong? import Foundation class CrashDetection: NSObject { private static let observedSignals = [SIGABRT, SIGILL, SIGSEGV, SIGFPE, SIGBUS, SIGPIPE, SIGTRAP] private static var previousSignalHandlers: [Int32:(@convention(c) (Int32) -> Void)] = [:] @objc class func start() { NSSetUncaughtExceptionHandler(CrashDetection.recieveException) observedSignals.forEach { signalType in let oldHandler = signal(signalType, CrashDetection.recieveSignal) CrashDetection.previousSignalHandlers[signalType] = oldHandler } } private static let recieveException: @convention(c) (NSException) -> Swift.Void = { (recieveException) -> Void in UserDefaults.standard.setValue(true, forKey: "crashDidOccur") } private static let recieveSignal: @convention(c) (Int32) -> Void = { (recievedSignal) -> Void in UserDefaults.standard.setValue(true, forKey: "crashDidOccur") NSSetUncaughtExceptionHandler(nil) observedSignals.forEach { signalType in signal(signalType, previousSignalHandlers[signalType]) } } }
2
0
540
Jul ’23
CTCellularPlanProvisioning.supportsCellularPlan returns false on eSIM supported devices (CRITICAL)
Working for a telephony provider, I had to implement something that checks if the device supports eSIM. And when checking on a device like iPhone 13 Pro it returns false. Why is that the case? Can someone help? var supportsESIM: Bool { cellularPlanProvisioning.supportsCellularPlan() } private let cellularPlanProvisioning = CTCellularPlanProvisioning()
3
0
282
Jul ’23
MetricKit and when or when not do we get reports?
The MetricKit implementation is pretty straight forward. I am testing it now for a couple of days, but I never saw any report passed to my test apps. (implemented it in an empty app that just crashes every now and then and in a product of ours) The function 'didReceive' is never called and each time I am asking 'MXMetricManager.shared.pastDiagnosticPayloads' I get an empty collection. So that is the secret here? Is MetricKit not working for development builds? Or are there other factors/requirements not meet? import Foundation import MetricKit class CrashDetection: NSObject, MXMetricManagerSubscriber { @objc static let shared = CrashDetection() @objc private override init() { } internal static var crashDidOccur: Bool { get { UserDefaults.standard.bool(forKey: crashDidOccurKey) ?? false } set { UserDefaults.standard.set(newValue, forKey: crashDidOccurKey) } } @objc func start() { MXMetricManager.shared.add(self) } @objc func stop() { MXMetricManager.shared.remove(self) } func didReceive(_ payloads: [MXDiagnosticPayload]) { let crashDiagnostics = payloads.compactMap({ $0.crashDiagnostics }) CrashDetection.crashDidOccur = crashDiagnostics.isEmpty == false } }
1
0
976
Jul ’23
WidgetExtension Cannot Access json File Created by Flutter
I have a CRUD app built with flutter. Now I want to use Swift to create a widget to show the data at home screen. I use json to store the data. In the following code if I replace jsonURL with mock json string, everything works well. So I think the problem comes from accessing the local file. let sharedContainerURL = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.app.identifier") let jsonURL = sharedContainerURL?.appendingPathComponent("things.json") And this is how I create the json file with Dart. Future<String> get _localPath async { final directory = await getApplicationDocumentsDirectory(); return directory.path; } Future<File> get _localFile async { final path = await _localPath; return File('$path/$storageName.json'); } In a nutshell the problem is that the widget cannot access the json file I created in the app storage. Everything works well except the widget.
0
0
290
Jul ’23
Symbol breadcrumb
Using Xcode (or Instruments), is there a way to know all the functions/symbols that are touched by a line of code? struct Test { private func intro() { } func partOne() { intro() } func partTwo() { partOne() } func partThree() { partTwo() print(credits) } private var credits: String { "" } } let test = Test() test.partTwo() // partTwo, partOne, intro test.partThree() // partThree, partTwo, partOne, intro, credits
3
0
1k
Jul ’23
iOS 14.4.0 Vector Kit Crash
Getting the crash only in iOS 14.x and i cannot identify the reason. Log: Crashed: com.apple.main-thread 0 VectorKit 0x324360 md::FrameGraphUtils::prepareGraphBuilderForRenderTarget(md::FrameGraphBuilder*, ggl::RenderTarget*, geo::StringLiteral, geo::StringLiteral, geo::StringLiteral) + 72 1 VectorKit 0x526f20 md::PassList::didPrepareForLayout(md::LayoutContext const&, md::Renderer&) + 276 2 VectorKit 0x526f20 md::PassList::didPrepareForLayout(md::LayoutContext const&, md::Renderer&) + 276 3 VectorKit 0x99dc4 md::CartographicRenderer::layout(md::LayoutContext&) + 120 4 VectorKit 0x8e2ac md::MapEngine::layoutScene(double, bool) + 664 5 VectorKit 0x8de5c -[_MapEngineRenderQueueSource renderQueueForTimestamp:] + 60 6 VectorKit 0x8ddf4 -[MDDisplayLayer _renderQueueForTimestamp:prepareHandler:] + 36 7 VectorKit 0x8ddc0 -[MDDisplayLayer renderQueueForTimestamp:] + 48 8 VectorKit 0x8d028 -[MetalLayer _onTimerFired:withPresent:] + 256 9 VectorKit 0x8c7b4 md::MapEngine::renderScene(double, std::__1::function<void ()>) + 100 10 VectorKit 0xca7a8 md::MapEngine::onRenderTimerFired(double) + 344 11 VectorKit 0x4ab388 std::__1::function<void (double)>::operator()(double) const + 48 12 VectorKit 0xca594 ggl::RunLoop::_RunLoopCallbacker::callback(double) + 144 13 VectorKit 0x63c2b8 ___ZN3ggl11DisplayLinkC2ENSt3__18functionIFvdEEE_block_invoke_2 + 92 14 libdispatch.dylib 0x4420 _dispatch_client_callout + 20 15 libdispatch.dylib 0x779c _dispatch_continuation_pop + 416 16 libdispatch.dylib 0x19298 _dispatch_source_invoke + 1260 17 libdispatch.dylib 0x11d04 _dispatch_main_queue_callback_4CF + 556 18 CoreFoundation 0xc39ec CFRUNLOOP_IS_SERVICING_THE_MAIN_DISPATCH_QUEUE + 16 19 CoreFoundation 0x82878 __CFRunLoopRun + 2508 20 CoreFoundation 0x81740 CFRunLoopRunSpecific + 600 21 HIToolbox 0x315c4 RunCurrentEventLoopInMode + 292 22 HIToolbox 0x313f4 ReceiveNextEventCommon + 688 23 HIToolbox 0x31124 _BlockUntilNextEventMatchingListInModeWithFilter + 76 24 AppKit 0x4182c _DPSNextEvent + 868 25 AppKit 0x401ac -[NSApplication(NSEvent) _nextEventMatchingEventMask:untilDate:inMode:dequeue:] + 1312 26 AppKit 0x32060 -[NSApplication run] + 600 27 AppKit 0x3804 NSApplicationMain + 1064 28 AppKit 0x2f56d4 _NSApplicationMainWithInfoDictionary + 22 29 UIKitMacHelper 0x4fc4 UINSApplicationMain + 1276 30 UIKitCore 0x2a60 UIApplicationMain + 164 31 libswiftUIKit.dylib 0x13688 $s5UIKit17UIApplicationMainys5Int32VAD_SpySpys4Int8VGGSgSSSgAJtF + 104 32 BilliyoClinicalPDN 0x1b898 main + 4377884824 (GoalProgressHeader.swift:4377884824) 33 libdyld.dylib 0x16f34 start + 4 Thread 0 libsystem_kernel.dylib 0x29c4 __workq_kernreturn + 8 1 libsystem_pthread.dylib 0x30ac _pthread_wqthread + 352 2 libsystem_pthread.dylib 0x1d94 start_wqthread + 8 Thread 0 libsystem_pthread.dylib 0x1d8c qos_class_main + 98 Thread 0 libsystem_kernel.dylib 0x29c4 __workq_kernreturn + 8 1 libsystem_pthread.dylib 0x30ac _pthread_wqthread + 352 2 libsystem_pthread.dylib 0x1d94 start_wqthread + 8 Thread 0 libsystem_kernel.dylib 0x29c4 __workq_kernreturn + 8 1 libsystem_pthread.dylib 0x30ac _pthread_wqthread + 352 2 libsystem_pthread.dylib 0x1d94 start_wqthread + 8 com.apple.uikit.eventfetch-thread 0 libsystem_kernel.dylib 0xce8 mach_msg_trap + 8 1 libsystem_kernel.dylib 0x1098 mach_msg + 76 2 CoreFoundation 0x83e98 __CFRunLoopServiceMachPort + 380 3 CoreFoundation 0x8236c __CFRunLoopRun + 1216 4 CoreFoundation 0x81740 CFRunLoopRunSpecific + 600 5 Foundation 0x64a88 -[NSRunLoop(NSRunLoop) runMode:beforeDate:] + 232 6 Foundation 0xf3254 -[NSRunLoop(NSRunLoop) runUntilDate:] + 124 7 UIKitCore 0x3ff4 -[UIEventFetcher threadMain] + 156 8 Foundation 0x5d0f4 NSThread__start + 864 9 libsystem_pthread.dylib 0x706c _pthread_start + 320 10 libsystem_pthread.dylib 0x1da0 thread_start + 8 Thread 0 libsystem_kernel.dylib 0x29c4 __workq_kernreturn + 8 1 libsystem_pthread.dylib 0x30ac _pthread_wqthread + 352 2 libsystem_pthread.dylib 0x1d94 start_wqthread + 8 Thread 0 libsystem_kernel.dylib 0x29c4 __workq_kernreturn + 8 1 libsystem_pthread.dylib 0x30ac _pthread_wqthread + 352 2 libsystem_pthread.dylib 0x1d94 start_wqthread + 8 Thread 0 libsystem_kernel.dylib 0x29c4 __workq_kernreturn + 8 1 libsystem_pthread.dylib 0x30ac _pthread_wqthread + 352 2 libsystem_pthread.dylib 0x1d94 start_wqthread + 8 Thread 0 libsystem_kernel.dylib 0x29c4 __workq_kernreturn + 8 1 libsystem_pthread.dylib 0x30ac _pthread_wqthread + 352 2 libsystem_pthread.dylib 0x1d94 start_wqthread + 8 Thread 0 libsystem_kernel.dylib 0x29c4 __workq_kernreturn + 8 1 libsystem_pthread.dylib 0x30ac _pthread_wqthread + 352 2 libsystem_pthread.dylib 0x1d94 start_wqthread + 8 com.google.firebase.crashlytics.MachExceptionServer 0 FirebaseCrashlytics 0x1ef98 FIRCLSProcessRecordAllThreads + 184 1 FirebaseCrashlytics 0x1f378 FIRCLSProcessRecordAllThreads + 1176 2 FirebaseCrashlytics 0x16618 FIRCLSHandler + 48 3 FirebaseCrashlytics 0x18dd8 FIRCLSMachExceptionServer + 688 4 libsystem_pthread.dylib 0x706c _pthread_start + 320 5 libsystem_pthread.dylib 0x1da0 thread_start + 8 com.apple.NSURLConnectionLoader 0 libsystem_kernel.dylib 0xce8 mach_msg_trap + 8 1 libsystem_kernel.dylib 0x1098 mach_msg + 76 2 CoreFoundation 0x83e98 __CFRunLoopServiceMachPort + 380 3 CoreFoundation 0x8236c __CFRunLoopRun + 1216 4 CoreFoundation 0x81740 CFRunLoopRunSpecific + 600 5 CFNetwork 0x24c7d0 _CFURLStorageSessionCopyCache + 36132 6 Foundation 0x5d0f4 NSThread__start + 864 7 libsystem_pthread.dylib 0x706c _pthread_start + 320 8 libsystem_pthread.dylib 0x1da0 thread_start + 8
1
0
417
Jul ’23
Arduino HM-10 Bluetooth with iOS : Connected, but it doesn't send values
I'm trying to make an iOS (SwiftUI based) app to connect the arduino and send the current latitude value of ios to arduino. I successfully made the view that allow user to select the bluetooth device, and the UUID/name of the device is successfully displayed. Also, the arduino device detects connection (I used LiquidCrystal to display serial and it says "OK+CONN" and "OK+LOST" if connection was lost.), but when I click "fetch location" button, nothing happens on arduino side. The code is in stackoverflow due to character limits: https://stackoverflow.com/questions/76752529/arduino-hm-10-bluetooth-with-ios-connected-but-it-doesnt-send-values
0
0
625
Jul ’23