Hello,
I am using SwiftUI and would like to publish my app on iPhone beforehand.
Post
Replies
Boosts
Views
Activity
Hello, The data are very important. These are data like a certain time, place or contents of a list. Mainly it is small strings that users enter.
But I would like to add documents later.
Okey, thanks a lot. How do the last two methods work, or where can you look at it?
It must be "0"
Yes, because when I call the image separately via "image("0"), it is displayed.
Yes, it is then simply all white
That worked. I can't thank you enough!
Thank you very much! Thanks to your tips and projects, it works for me now. You have helped me a lot and to this extent is not self-evident!
Do you mean alerts that occur in your app, or messenges from other apps like iMessage. Because the system notifications or from other apps always come on the top right.
Changed the code again and tried other approaches. Have asked the question again because of this. I load the items from the Item entity. The items are added in the ContentView. Tested with a print-statement that there the Ids are created correctly and also each item has a different one. Only in the EditView it always takes the same ID of the last added item. Also was first the problem that the Ids are randomly selected. Now it always selects the one of the last added item.
Changed the code again and tried other approaches. Have asked the question again because of this. I load the items from the Item entity. The items are added in the ContentView. Tested with a print-statement that there the Ids are created correctly and also each item has a different one. Only in the EditView it always takes the same ID of the last added item. Also was first the problem that the Ids are randomly selected. Now it always selects the one of the last added item.
The ContentView, where the item is set:
//
// ContentView.swift
// CoreData_T
//
// Created by Janik Hartmann on 31.12.22.
//
import SwiftUI
import CoreData
import Foundation
struct ContentView: View {
@Environment(\.managedObjectContext) private var viewContext
//Abfrage zum Anzeigen
@FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Item.name, ascending: false)],
animation: .default)
//Referenz zum Entity Item
var items: FetchedResults<Item>
@State private var name: String = ""
// Test
@State private var editName = ""
@State private var showeditsheet = false
var body: some View {
NavigationView {
VStack{
TextField("Text eingeben", text: $name)
.padding()
Button {
addItem()
} label: {
Text("Save")
}.padding()
List {
ForEach(items, id: \.self) { item in
NavigationLink(destination: ToDo(list:item)) {
HStack {
Text(item.name ?? "Not found")
Button {
self.showeditsheet = true
} label: {
Text("Edit")
}.buttonStyle(.bordered)
}
}
.sheet(isPresented: $showeditsheet){
EditSheet(itemId: item.id!, item:item)
}
}
.onDelete(perform: deleteItems)
}
}
}
}
//MARK: - Hinzufügen der Listen
private func addItem() {
withAnimation {
let newItem = Item(context: viewContext)
newItem.name = name
newItem.id = UUID()
do {
try viewContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
}
private func deleteItems(offsets: IndexSet) {
withAnimation {
offsets.map { items[$0] }.forEach(viewContext.delete)
do {
try viewContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
}
}
Ok
import SwiftUI
import CoreData
import Foundation
struct ContentView: View {
@Environment(\.managedObjectContext) private var viewContext
//Abfrage zum Anzeigen
@FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Item.name, ascending: false)],
animation: .default)
//Referenz zum Entity Item
var items: FetchedResults<Item>
@State private var name: String = ""
// Test
@State private var editName = ""
@State private var showeditsheet = false
var body: some View {
NavigationView {
VStack{
TextField("Text eingeben", text: $name)
.padding()
Button {
addItem()
} label: {
Text("Save")
}.padding()
List {
ForEach(items, id: \.self) { item in
NavigationLink(destination: ToDo(list:item)) {
HStack {
Text(item.name ?? "Not found")
Button {
self.showeditsheet = true
} label: {
Text("Edit")
}.buttonStyle(.bordered)
}
}
.sheet(isPresented: $showeditsheet){
EditSheet(itemId: item.id!, item:item)
}
}
.onDelete(perform: deleteItems)
}
}
}
}
//MARK: - Hinzufügen der Listen
private func addItem() {
withAnimation {
let newItem = Item(context: viewContext)
newItem.name = name
newItem.id = UUID()
do {
try viewContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
}
private func deleteItems(offsets: IndexSet) {
withAnimation {
offsets.map { items[$0] }.forEach(viewContext.delete)
do {
try viewContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
}
}
import SwiftUI
import Foundation
import CoreData
struct EditSheet: View {
@Environment(\.managedObjectContext) private var viewContext
@Environment(\.dismiss) private var dismiss
@State private var name: String = ""
private var item: Item
var itemid: UUID
init(itemId: UUID, item: Item) {
self.item = item
self.itemid = item.id!
self.name = item.name ?? ""
}
var body: some View {
VStack{
TextField("Text eingeben", text: $name)
.padding()
Button {
update(item: item, itemid: item.id!)
dismiss()
} label: {
Text("Save")
}.padding()
}.onAppear{
name = item.name!
}
}
func update(item:Item, itemid id: UUID){
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Item")
fetchRequest.predicate = NSPredicate(format: "id == %@", id as CVarArg)
do {
let results = try viewContext.fetch(fetchRequest) // Rufe den Fetchrequest auf
if results.count > 0 {
let objectToUpdate = results[0] // Nehme das erste
if objectToUpdate.value(forKey: "id") as? UUID == id {
objectToUpdate.setValue(name, forKey: "name") //Editiere den Key "name" zum übergebenen Wert
do {
try viewContext.save() // Speichern
print("Erfolgreich gespeichert!")
} catch let error as NSError {
print("Fehler beim Speichern. \(error), \(error.userInfo)")
}
} else {
print("Fehler: das aktualisierte Element hat eine andere ID als die übergebene.")
}
} else {
print("Fehler: keine Ergebnisse für die angegebene ID gefunden.")
}
} catch let error as NSError {
print("Fehler beim Fetchen. \(error), \(error.userInfo)")
}
}
}
editname is from an earlier version. Here it is without meaning.
Id when I press the Edit button on the ContenView: 78AB2468-CA12-4A3B-8C55-67F366FDFE7D
Id when I press the Save button on the EditView: BCC1267C-ACF6-4926-9BE8-5C4D8062E108
Id the update func print: BCC1267C-ACF6-4926-9BE8-5C4D8062E108
objecttoupdate:
<Item: 0x600001196bc0> (entity: Item; id: 0x81a3114acc5b93d0 x-coredata://8BCB76FB-F8F2-43CE-B703-1E6C1BB03811/Item/p3;
data: {
id = "BCC1267C-ACF6-4926-9BE8-5C4D8062E108";
liste =( );
name = Asdfasdf;
timestamp = nil;
})
I therefore believe that the update func also works. But the func does not get the ID of the selected object. The first print ID in the ContentView always changes depending on the object. The other IDs are always the same, as if it always selects the same object only. Or does not get the correct ID transmitted.
Sorry.
import SwiftUI
import CoreData
import Foundation
struct ContentView: View {
@Environment(\.managedObjectContext) private var viewContext
@FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Item.name, ascending: false)],
animation: .default)
var items: FetchedResults<Item>
@State private var name: String = ""
@State private var showeditsheet = false
var body: some View {
NavigationView {
VStack{
TextField("Text eingeben", text: $name)
.padding()
Button {
addItem()
} label: {
Text("Save")
}.padding()
List {
ForEach(items, id: \.self) { item in
NavigationLink(destination: ToDo(list:item)) {
HStack {
Text(item.name ?? "Not found")
Button {
print(item.id)
self.showeditsheet = true
} label: {
Text("Edit")
}.buttonStyle(.bordered)
}
}
.sheet(isPresented: $showeditsheet){
EditSheet(itemId: item.id!, item:item)
}
}
.onDelete(perform: deleteItems)
}
}
}
}
//MARK: - Hinzufügen der Listen
private func addItem() {
withAnimation {
let newItem = Item(context: viewContext)
newItem.name = name
newItem.id = UUID()
do {
try viewContext.save()
} catch {
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
}
private func deleteItems(offsets: IndexSet) {
withAnimation {
offsets.map { items[$0] }.forEach(viewContext.delete)
do {
try viewContext.save()
} catch {
let nsError = error as NSError
fatalError("Unresolved error \(nsError), \(nsError.userInfo)")
}
}
}
}
import SwiftUI
import Foundation
import CoreData
struct EditSheet: View {
@Environment(\.managedObjectContext) private var viewContext
@Environment(\.dismiss) private var dismiss
@State private var name: String = ""
private var item: Item
var itemid: UUID
init(itemId: UUID, item: Item) {
self.item = item
self.itemid = item.id!
self.name = item.name ?? ""
}
var body: some View {
VStack{
TextField("Text eingeben", text: $name)
.padding()
Button {
print(item.id)
update(item: item, itemid: item.id!)
dismiss()
} label: {
Text("Save")
}.padding()
}.onAppear{
name = item.name!
}
}
func update(item:Item, itemid id: UUID){
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "Item")
fetchRequest.predicate = NSPredicate(format: "id == %@", id as CVarArg)
do {
let results = try viewContext.fetch(fetchRequest)
if results.count > 0 {
let objectToUpdate = results[0]
if objectToUpdate.value(forKey: "id") as? UUID == id {
objectToUpdate.setValue(name, forKey: "name")
do {
print (id)
print(objectToUpdate)
try viewContext.save()
print("Erfolgreich gespeichert!")
} catch let error as NSError {
print("Fehler beim Speichern. \(error), \(error.userInfo)")
}
} else {
print("Fehler")
}
} else {
print("Fehler")
}
} catch let error as NSError {
print("Fehler beim Fetchen. \(error), \(error.userInfo)")
}
}
}