I'm currently trying to save a selected image in core data as a type data, but I'm getting an error in the persistence file marked with a comment. I've included my code and any questions I will gladly answer. Thanks for any help!
Content View:
import SwiftUI
import PhotosUI
struct ContentView: View {
@ObservedObject var persistence = PersistenceController.shared
@State var selectedItems: [PhotosPickerItem] = []
@State var data: Data?
var body: some View {
NavigationView{
VStack{
Spacer()
VStack{
Spacer()
if let data = data, let uiimage = UIImage(data: data) {
Image(uiImage: uiimage)
.resizable()
.scaledToFit()
.frame(width: 250, height: 500)
}
Spacer()
}
Spacer()
PhotosPicker(selection: $selectedItems, maxSelectionCount: 1, matching: .images){
Text("Pick Photo")
}
.onChange(of: selectedItems){ newValue in
guard let item = selectedItems.first else{
return
}
item.loadTransferable(type: Data.self){ result in
switch result {
case .success(let data):
if let data = data{
self.data = data
} else {
print("Data is nil")
}
case .failure(let failure):
fatalError("\(failure)")
}
}
}
Spacer()
}
.navigationBarItems(trailing: addButton)
}
}
var addButton: some View {
Button(action: {
guard let item = selectedItems.first else{
return
}
item.loadTransferable(type: Data.self){ result in
switch result {
case .success(let data):
if let data = data{
persistence.addObject(image: data)
} else {
print("Data is nil")
}
case .failure(let failure):
fatalError("\(failure)")
}
}
}){
Text("Add Image").bold()
}
}
}
Persistence:
import Foundation
import CoreData
class PersistenceController: ObservableObject {
static let shared = PersistenceController()
let container: NSPersistentContainer
init(inMemory: Bool = false) {
container = NSPersistentContainer(name: "ReciPlanner")
if inMemory {
container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
}
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
container.viewContext.automaticallyMergesChangesFromParent = true
}
func addObject(image: Data){
let context = container.viewContext
let object = Object(context: context) //Error: Thread 7: "An NSManagedObject of class 'Object' must have a valid NSEntityDescription."
object.item = image
}
func contextSave() {
let context = container.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
print("**** ERROR: Unable to save context \(error)")
}
}
}
}
Data Model:
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
I'm currently trying to save a selected image in core data as a type data, but I'm getting an error in the persistence file marked with a comment. I've included my code and any questions I will gladly answer. Thanks for any help!
Content View:
import SwiftUI
import PhotosUI
struct ContentView: View {
@ObservedObject var persistence = PersistenceController.shared
@State var selectedItems: [PhotosPickerItem] = []
@State var data: Data?
var body: some View {
NavigationView{
VStack{
Spacer()
VStack{
Spacer()
if let data = data, let uiimage = UIImage(data: data) {
Image(uiImage: uiimage)
.resizable()
.scaledToFit()
.frame(width: 250, height: 500)
}
Spacer()
}
Spacer()
PhotosPicker(selection: $selectedItems, maxSelectionCount: 1, matching: .images){
Text("Pick Photo")
}
.onChange(of: selectedItems){ newValue in
guard let item = selectedItems.first else{
return
}
item.loadTransferable(type: Data.self){ result in
switch result {
case .success(let data):
if let data = data{
self.data = data
} else {
print("Data is nil")
}
case .failure(let failure):
fatalError("\(failure)")
}
}
}
Spacer()
}
.navigationBarItems(trailing: addButton)
}
}
var addButton: some View {
Button(action: {
guard let item = selectedItems.first else{
return
}
item.loadTransferable(type: Data.self){ result in
switch result {
case .success(let data):
if let data = data{
persistence.addObject(image: data)
} else {
print("Data is nil")
}
case .failure(let failure):
fatalError("\(failure)")
}
}
}){
Text("Add Image").bold()
}
}
}
Persistence:
import Foundation
import CoreData
class PersistenceController: ObservableObject {
static let shared = PersistenceController()
let container: NSPersistentContainer
init(inMemory: Bool = false) {
container = NSPersistentContainer(name: "ReciPlanner")
if inMemory {
container.persistentStoreDescriptions.first!.url = URL(fileURLWithPath: "/dev/null")
}
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
container.viewContext.automaticallyMergesChangesFromParent = true
}
func addObject(image: Data){
let context = container.viewContext
let object = Object(context: context) //Error: Thread 7: "An NSManagedObject of class 'Object' must have a valid NSEntityDescription."
object.item = image
}
func contextSave() {
let context = container.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
print("**** ERROR: Unable to save context \(error)")
}
}
}
}
Data Model:
So I was trying to save an image in core data and created an NSManagedObject Subclass. After doing so I decided I didn't like it so I deleted the files, but now every time I run the project it creates a properties file with an error saying it can't find a UIImage in scope and the file isn't editable so I can't import UIKit. I've tried deleting the file in finder, deleting the whole project and then redownloading it from GitHub, but to no avail. Basically I want it to stop making the subclass every time I run the project.
Please help. Thanks!
So I'm looking to add a button to my app that would create and fill a reminder in the user's Reminders app, but I've found that I first need to request access to the user's Reminders app data. I've also found the way to do that has been changed with iOS 17 as explained here: https://developer.apple.com/documentation/eventkit/ekeventstore/4162273-requestfullaccesstoreminders
How do I use this function so that the prompt requesting for access to the user's Reminders app pops up at the launch of the app every time unless they've previously given permission?
Also what would be the function to create the reminder once I do have permissions? This is the code ChatGPT gave me to do so, but I just keep getting "Failed to create Reminder URL".
func createReminder() {
let reminderTitle = "Cocktail Groceries"
var subtaskStrings: [String] = []
for ingredient in shoppingList {
subtaskStrings.append(ingredient)
}
let subtasks = subtaskStrings.map { (ingredient) -> [String: Any] in
return [
"title": ingredient,
"completed": false
]
}
let reminderData: [String: Any] = [
"title": reminderTitle,
"subtasks": subtasks
]
if let reminderURL = createURL(for: "x-apple-reminder://", with: reminderData) {
UIApplication.shared.open(reminderURL)
} else {
print("Failed to create Reminder URL")
}
}
Also I intend on expanding this function to the notes app. But im taking one step at a time.
Any help would be GREATLY appreciated. Thanks!
So I want to implement the same feature many apple made have which is an gray list of options when something is held. An example of this is when you hold down an iMessage chat before you open it and it gives the options to “Pin”, “Hide Alerts”, and “Delete” and shown here:
Additionally when you hold down an app as if you were going to delete it a menu of options show up:
Using a button how can I do this on a long hold? Any help or any direction toward help is greatly appreciated. All the best!
I need to be able to search my list of recipes given a string. I’m unsure how to filter a data model in core data though. I tried a ForEach(container){ recipe in, but it said it gave me an error. Anyone know the correct way in the scrappy way doesn’t work? Thanks
data controller:
import Foundation
import CoreData
class DataController: ObservableObject {
let container = NSPersistentContainer(name: "RecipeModel")
init() {
container.loadPersistentStores { desc, error in
if let error = error {
print("Failed to load the data \(error.localizedDescription)")
}
}
}
func save(context: NSManagedObjectContext) {
do {
try context.save()
print("Data saved")
} catch {
print("The data could not be saved")
}
}
func addRecipe(title: String, ingredients: [String], instructions: [String], notes: String, context: NSManagedObjectContext){
let recipe = Recipe(context: context)
recipe.id = UUID()
recipe.date = Date()
recipe.title = title
recipe.ingredients = ingredients
recipe.instructions = instructions
recipe.notes = notes
save(context: context)
}
func editRecipe(recipe: Recipe, title: String, ingredients: [String], instructions: [String], notes: String, context: NSManagedObjectContext){
recipe.title = title
recipe.ingredients = ingredients
recipe.instructions = instructions
recipe.notes = notes
save(context: context)import Foundation
}
func updateDate(recipe: Recipe, context: NSManagedObjectContext){
recipe.date=Date()
save(context: context)
}
}
So I have a sheet View for when I add a recipe to my program, but when I add an instruction I want the user to be able to click their entry and check it to see if it is correct so what I’ve done is add a text view to enlarge it, but when I go to the view it shows the nav bar of the previous view like this:
This only happens when I use a sheet.
So I’ve looked this up so many times and tried every way I’ve found using a @State variable and nothing works. I need a button that toggles between SystemImage: “Star” to SystemImage: “Star.fill” when clicked. And I want it to happen when it’s clicked. Everything I’ve tried only changes when I close and reopen the view because it happens on appearance. Is there any way to make it change instantly? Thanks for any help!
I would like to implement the “Toolbar” kind of thing above the keyboard shown in the image that includes an up and down arrow to iterate through text fields and a done button to dismiss the keyboard. How do I do this? Thanks!
So I’ve looked this up so many times and tried every way I’ve found using a @State variable and nothing works. I need a button that toggles between SystemImage: “Star” to SystemImage: “Star.fill” when clicked. And I want it to happen when it’s clicked. Everything I’ve tried only changes when I close and reopen the view because it happens on appearance. Is there any way to make it change instantly? Thanks for any help!
I am trying to implement a search bar in my recipe storage app. I got recommended using the .filter function that I didn’t know could be used on FetchedResults. So I did and now I’m getting errors, but not ones saying that it isn’t in the scope so I believe this is possible, just now sure how.
The ForEach loop containing the filter:
•ForEach(recipes.filter({$0.title.contains(searchingFor)})) { recipe in
Note: Recipes is just a FetchedResults type and searchingFor is just a string that comes from the search bar.
The errors:
•Value of optional type 'String?' must be unwrapped to refer to member 'contains' of wrapped base type 'String'
•Chain the optional using '?' to access member 'contains' only for non-'nil' base values
•Force-unwrap using '!' to abort execution if the optional value contains 'nil'
Any help is greatly appreciated.
Whenever I open a text field almost anywhere I get this common toolbar above my keyboard with two arrows that iterate through text fields and a done button. Not just on Apple related things, but even when I search on google. Which leads me to believe this is a default object and that google did not take the time to make an identical keyboard toolbar as all of Apple’s. So how do I get this default toolbar?
toolbar:
So I have a core data entity titled recipe. I'm trying to make a search bar to search the list of recipes and my method of doing so is doing a fetch request of all objects and converting it to an array of those objects and then filtering the array and displaying the results. Any idea as to how to convert a type fetch results to an array?
PS: as I'm typing this it occurred to me I could just do a for each loop and add them to the array as I go, but is there a quicker way to do this? Like a function? Thanks!!!
I'm currently (obviously) building an app and I decided I prefer the dark mode theme more than default. Is there any way I could set it so that dark mode is the default color of the app?
Does anyone have any clue as to how to get rid of the grey background of my list? I've actually tried everything I could find online. .background(Color.clear), .backgroundStyle(.clear), init(){...}. nothing. I even tried replicating it in a new project and it didn't even show up there. Any idea as to how to get rid of this?