Hi,
I am trying to create a local backup + restore when using SwiftUI and CoreData but I am facing errors left and right. the latest error I am stuck on is:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'executeFetchRequest:error: A fetch request must have an entity.'
Here is what am trying to do:
Creating a backup (already solved using NSPersistentStoreCoordinator.migratePersistentStore(_:to:options:type:))
Create a new NSPersistentContainer and call its NSPersistentContainer.loadPersistentStores(completionHandler:) (already solved, load is successful)
Update the .environment(.managedObjectContext, viewModel.context) so that SwiftUI uses the new context. (HERE is where the error appears)
Any help would be appreciated.
Here is some sample code of SwiftUI part of the main view:
class ViewModel: ObservableObject {
@Published var context: NSManagedObjectContext
}
@main
struct MyApp: App {
@StateObject var viewModel: ViewModel
var body: some Scene {
WindowGroup {
ContentView()
.environment(\.managedObjectContext, viewModel.context)
}
}
}
Post
Replies
Boosts
Views
Activity
Hi,
Since iOS 18 we now have a built-in "tap on item to scroll to the top" functionality into TabView, which is great but it does have a UI glitch on real devices, it works correct on simulators running from Xcode.
The real device I am testing is on iOS 18.2.1
It looks like this:
If I then try to scroll the list it snaps back to a offset bellow the navigation title, so fro the looks of it the "scroll to top" was not really to the top but some offset under it.
The View is declared like this:
struct ContentView: View {
private var tabSelection: Binding<String> { Binding(
get: { selectedTab },
set: { selectedTab = $0 }
)}
@State private var selectedTab: String = "Test"
var body: some View {
TabView(selection: tabSelection,
content: {
NavigationStack {
List {
ForEach(0...1000, id: \.self) { index in
Text("Test 1 - Row: \(index)")
}
}
.navigationTitle("Test 1")
}
.listStyle(.insetGrouped)
.tabItem {
Image(systemName: SFSystemName.morning)
Text("Test")
}
.tag("Test")
})
.tabViewStyle(.sidebarAdaptable)
}
}
Any ideas how to resolve this.
Hi,
After adding searchable to my view I see that here is no "voice input icon" in the top right of the field. Everything works if I open the keyboard and start voice input from there.
It looks like this:
Is there a way too show this "mic" icon like it shows in settings? In settings it looks like this:
Its important to note that this same app did not have this issue in iOS 17.
Ever since iOS 18 I have noticed that when application written in SwiftUI uses Label with the default color (which auto changes between light and dark appearance), from time to time when resuming an application that has been in the background, the color of those labels (only the Label elements) switches from the opposite to the correct one. Here is an example:
Steps to reproduce
Phone is in dark appearance
Open app
Labels text color is white and labels background is black
Go to home so that app is on background
Wait random time (does not happen all the time), some times 1 min some times 10
Reopen the application.
During the opening transition the Label text color was changed while the app was in suspended mode to the light appearance variant (black)
Once the app opening transition finishes the Label text color switches back to the correct color for dark appearance (white)
Same issue happens if you start from light appearance. I cannot reproduce this on Xcode simulators, I have tried to force memory warning to check if that has anything to do with it but that also does not cause the issue to appear on simulators. For now I can only reproduce this on real device.
Screenshots
Here is screenshots of the above example:
During transition
After transition
Hi,
After running the Xcode template "New project > (SwiftUI, SwiftData)" I noticed that there is no insert animation into the list.
The project is a pure vanilla project created from Xcode (Version 16.2 (16C5032a)) and the code is a simple as it gets:
//
// ContentView.swift
//
import SwiftUI
import SwiftData
struct ContentView: View {
@Environment(\.modelContext) private var modelContext
@Query private var items: [Item]
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))
}
}
.onDelete(perform: deleteItems)
}
.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
EditButton()
}
ToolbarItem {
Button(action: addItem) {
Label("Add Item", systemImage: "plus")
}
}
}
} detail: {
Text("Select an item")
}
}
private func addItem() {
withAnimation {
let newItem = Item(timestamp: Date())
modelContext.insert(newItem)
}
}
private func deleteItems(offsets: IndexSet) {
withAnimation {
for index in offsets {
modelContext.delete(items[index])
}
}
}
}
#Preview {
ContentView()
.modelContainer(for: Item.self, inMemory: true)
}
As you see the template's code does have withAnimation inside addItem but there is no animation. The new added item appears without animation in the the List
Here is a short video. Is this a known bug?
Hi,
This issue started with iOS 18, in iOS 17 it worked correctly. I think there was a change in SectionedFetchRequest so maybe I missed it but it did work in iOS 17.
I have a List that uses SectionedFetchRequest to show entries from CoreData. The setup is like this:
struct ManageBooksView: View {
@SectionedFetchRequest<Int16, MyBooks>(
sectionIdentifier: \.groupType,
sortDescriptors: [SortDescriptor(\.groupType), SortDescriptor(\.name)]
)
private var books: SectionedFetchResults<Int16, MyBooks>
var body: some View {
NavigationStack {
List {
ForEach(books) { section in
Section(header: Text(section.id)) {
ForEach(section) { book in
NavigationLink {
EditView(book: book)
} label: {
Text(book.name)
}
}
}
}
}
.listStyle(.insetGrouped)
}
}
}
struct EditView: View {
private var book: MyBooks
init(book: MyBooks) {
print("Init hit")
self.book = book
}
}
Test 1: So now when I change name of the Book entity inside the EditView and do save on the view context and go back, the custom EditView is correctly hit again.
Test 2: If I do the same changes on a different attribute of the Book entity the custom init of EditView is not hit and it is stuck with the initial result from SectionedFetchResults.
I also noticed that if I remove SortDescriptor(\.name) from the sortDescriptors and do Test 1, it not longer works even for name, so it looks like the only "observed" change is on the attributes inside sortDescriptors.
Any suggestions will be helpful, thank you.
The project setup is as follows:
Uses pods
Has swift bridging header as it uses both Objc and Swift
With Xcode Version 16.0 (16A242d), when building the project everything is fine but when I build the Documentation (Product > Build Documentation), I am getting this error via:
/.../Project/Pods/FirebaseCore/FirebaseCore/Sources/Public/FirebaseCore/FIRLoggerLevel.h:23:28: redefinition of 'FIRLoggerLevel'
...
Building the documentation of the same project with Xcode Version 15.4 works just fine, so the error must come from the new xcodebuild (Xcode 16.0 Build version 16A242d).
Here are the pods in the project:
pod 'Firebase/Crashlytics', '10.29.0'
pod 'Firebase/Performance', '10.29.0'
# (Recommended) Pod for Google Analytics
pod 'FirebaseAnalytics', '10.29.0'
pod 'GoogleAnalytics', '3.21'
pod 'GoogleTagManager', '7.4.3'
pod 'FirebaseRemoteConfig', '10.29.0'
pod 'GoogleUtilities', '7.13.0'
Tried with all latest, but the same issue persists.
Any ideas, on how to resolve this? I read that it is not possible to disable the pods being build by docc as they are dependencies of the target which is being build by the docc process, if that is not true, maybe I can disable docc from building the Pods.
I am in the process of evaluating Swift 6 and I noticed that when using the completion handler version of the requestAuthorization the application crashes with EXC_BAD_INSTRUCTION exception.
Using this code:
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound, .badge]) { success, error in
print(success)
}
Crashes when the project is build with Swift 6 and works normalising when build with Swift 5.
The only solution that I have found so far is to switch to using the async version of that API:
Task {
let center = UNUserNotificationCenter.current()
do {
if try await center.requestAuthorization(options: [.alert, .sound, .badge]) == true {
print("success")
} else {
print("fail")
}
} catch {
print("Error")
}
}
Is the a known issue?
I have submitted feedback with ID "FB15294185".
Since iOS 18 I have noticed a strange issue which happens to the TabView in SwiftUI when you switch from Dark to Light mode.
With this code:
import SwiftUI
struct ContentView: View {
var body: some View {
TabView {
List {
ForEach(0..<100, id: \.self) { index in
Text("Row: \(index)")
}
}.tabItem {
Image(systemName: "house")
Text("Home")
}
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
The TabBar does not switch colours when going from dark to light, it work correctly when going from light to dark.
Here is a video of iOS 18 with the issue:
Here is a video of iOS 17.5 with same code and no issue:
On real device it looks (better), the color does update but with delay.
I have submitted a feedback bug report, but in the meanwhile has anyone been back to resolve this?
Hi,
It seams that the public func isSuperset(of other: CharacterSet) -> Bool API gives inconsistent results for some emoji symbols when uses with and without prefix text. Here is a playground example:
import Foundation
let input1 = "🥀"
let input11 = "a🥀"
let input2 = "😀"
let input22 = "a😀"
let letters = CharacterSet.letters
print("'\(input1)' is part of 'CharacterSet.letters': \(letters.isSuperset(of: CharacterSet(charactersIn: input1)))") // Gives false
print("'\(input11)' is part of 'CharacterSet.letters': \(letters.isSuperset(of: CharacterSet(charactersIn: input11)))") // INCORRECT: Should give false, but it gives true
print("'\(input2)' is part of 'CharacterSet.letters': \(letters.isSuperset(of: CharacterSet(charactersIn: input2)))") // Gives false
print("'\(input22)' is part of 'CharacterSet.letters': \(letters.isSuperset(of: CharacterSet(charactersIn: input22)))") // Gives false
Output:
'🥀' is part of 'CharacterSet.letters': false
'a🥀' is part of 'CharacterSet.letters': true
'😀' is part of 'CharacterSet.letters': false
'a😀' is part of 'CharacterSet.letters': false
Has anyone observed this?
The idea is to make it easer to update documentation when API changes or when code is not correct.
Is it possible to make the code file declared like this:
@Code(name: "AppDelegate.swift", file: AppDelegate.swift)
And the content of the AppDelegate.swift file is:
import UIKit
@main
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
compiler error should be raised here
return true
}
}
After doing "Product > Build Documentation" the output gives the following documentation and there is not warning or errors during the build:
Thank you for your answers.
If you handle textField(_:shouldChangeCharactersIn:replacementString:) and return false for a paste operation, once user does and "shake to undo" the provided range is out of bounds of the text field's text. Is this expected?
Here is a sample code that simply limits the input to 5 characters:
class ViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var textField: UITextField!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
textField.delegate = self
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let text = textField.text ?? ""
let currentString = text as NSString
let newString = currentString.replacingCharacters(in: range, with: string)
return newString.count < 5
}
}
Steps to reproduce a the crash:
UsernameTextFieldShake[40533:8359309] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString replaceCharactersInRange:withString:]: Range or index out of bounds'
Type "test"
Copy the text
Paste the text at the end of the text field's text
The paste will not be allowed as it is above 5 length.
Shake the device
Press undo
Crash, due to let newString = currentString.replacingCharacters(in: range, with: string)
Is there a correct way to guard agains this "rogue" range?
Is this range expected to be provided to the textField(_:shouldChangeCharactersIn:replacementString:), one might think because the previous handling returned false that the undo should happen on the previous accepted command (which was at step 1)
Thank you for the responses.
With iOS 17 creation of HKWorkout is deprecated via its init functions and the recommendation is to use HKWorkoutBuilder. If you try to init HKWorkout like you would pre iOS 17 you get this warning of deprecation:
The problem is that I am creating this HKWorkout object inside unit tests in order to test a service that works with such objects. And HKWorkoutBuilder requires a HKHealthStore which itself requires to be authenticated to be able to create HKWorkoutActivity instances, like it would be when an app is running. But since the unit tests cannot accept the request on the HKHealthStore I am not sure if using HKWorkoutBuilder inside unit tests is possible.
I've also tried to inherit HKHealthStore and override all of its methods, but still, store requires authorization.
Any ideas on how to proceed with creating HKWorkout for unit test purposes?
Hi, I want to enable swipeActions for some rows of a List while other rows do not have this action.
Here is an example:
List {
ForEach(1..<100) { i in
Text("\(i)")
.swipeActions(edge: .leading) {
Button {
total += i
} label: {
Label("Add \(i)", systemImage: "plus.circle")
}
.tint(.indigo)
}
.swipeActions(edge: .trailing) {
Button {
total -= i
} label: {
Label("Subtract \(i)", systemImage: "minus.circle")
}
}
}
}
What would be the best approach to disable the swipeActions for let say the 50 row?
Hi, with iOS 17 creation of HKWorkout is deprecated via its init functions and the recommendation is to use HKWorkoutBuilder:
The problem is that I am creating this HKWorkout object inside unit tests in order to test a service that works with such objects. And HKWorkoutBuilder requires a HKHealthStore which itself requires to be authenticated to be able to create HKWorkoutActivity instances, like it would be when an app is running. But since the unit tests cannot accept the request on the HKHealthStore I am not sure if using HKWorkoutBuilder inside unit tests is possible.
Any ideas on how to proceed with creating HKWorkout for unit test purposes?