Hello, how do I fix "Thread 1: "NSFetchRequest could not locate an NSEntityDescription for entity name 'Goal'"
import SwiftUI
import SwiftData
@main
struct Main: App {
@Environment(\.scenePhase) private var scenePhase
@StateObject var statsViewModel = StatsViewModel()
@StateObject var badgeViewModel = BadgeViewModel()
@StateObject var localNotificationManager = LocalNotificationManager()
@AppStorage("notifications") var notificationsSet: Bool = false
@Environment(\.modelContext) private var modelContext
var body: some Scene {
WindowGroup {
ContentView()
.environmentObject(statsViewModel)
.environmentObject(badgeViewModel)
.environmentObject(localNotificationManager)
.task {
if !notificationsSet {
do{
try await localNotificationManager.reqeustAuthorization()
await localNotificationManager.setUpNotificationsAtStart()
} catch{
}
}
notificationsSet = true
}
}
.modelContainer(container)
.onChange(of: scenePhase) { _, phase in
if phase == .active{
Task{
await localNotificationManager.getCurrentSettings()
await localNotificationManager.getPendingRequest()
}
} else if phase == .background{
do {
try modelContext.save()
} catch {
print("COULD NOT SAVE WITH SWIFTDATA")
}
}
}
}
}
and
@MainActor
var container: ModelContainer = {
let fileContainer = URL.storeURL(for: "group.Water-Alert-App", databaseName: "CoreData")
let defaultDirectoryURL = NSPersistentContainer.defaultDirectoryURL()
let localSchema = Schema([Reminder.self])
let cloudSchema = Schema([Goal.self, WaterData.self, Container.self])
let localConfiguration = ModelConfiguration("Local", schema: localSchema, url: defaultDirectoryURL.appendingPathComponent("Local.sqlite"))
let cloudConfiguration = ModelConfiguration("Cloud", schema: cloudSchema, url: fileContainer, cloudKitDatabase: .private("iCloud.Water-Alert-App-Offical"))
let container = try! ModelContainer(for: Reminder.self, Goal.self, WaterData.self, Container.self, configurations: localConfiguration, cloudConfiguration)
return container
}()
this is the code that makes the app crash
Thank You
Selecting any option will automatically load the page
Post
Replies
Boosts
Views
Activity
Hello
I'm making an app that displays large Double numbers, for example 86,859.002. The problem is how do I change the comma( , ) with the dot ( . )
Thank you
Hello
I'm trying to decode a JSON File but it's not working and I can't understand why
Code:
import SwiftUI
struct Search: View {
let sf: [SF] = Bundle.main.decode("sf.json")
@State private var searchText: String = ""
var body: some View {
NavigationView{
Form {
Section(header: Text("Search bar")){
TextField("Search", text: $searchText)
.padding(7)
.background(Color(.systemGray6))
.cornerRadius(8)
}
Section(){
List{
ForEach(sf) { item in
Text(item.title)
}
}
}
}
.navigationTitle("SF")
}
}
}
struct SF: Codable, Identifiable {
var id: String
var title: String
var items: [String]
}
extension Bundle {
func decode<T: Codable>(_ file: String) -> T {
guard let url = self.url(forResource: file, withExtension: nil) else {
fatalError("Failed to locate \(file) in bundle.")
}
guard let data = try? Data(contentsOf: url) else {
fatalError("Failed to load \(file) from bundle.")
}
let decoder = JSONDecoder()
guard let loaded = try? decoder.decode(T.self, from: data) else {
fatalError("Failed to decode \(file) from bundle.")
}
return loaded
}
}
Here is the JSON file
[
{
"id": "all"
"title": "All",
"items": [
"square.and.arrow.up",
"square.and.arrow.up.fill",
"square.and.arrow.down"
]
}
]
Thank you
Hello
How di i fix the error at line 16: I
nstance member 'deci' cannot be used on type 'BMIView'; did you mean to use a value of this type instead?
import SwiftUI
struct BMIView: View {
@State var deci = "3"
var numberFormatter: NumberFormatter = {
let nf = NumberFormatter()
nf.locale = Locale.current
nf.numberStyle = .decimal
nf.maximumFractionDigits = Int(deci) ?? 0
return nf
}()
@State private var height = ""
@State private var weight = ""
@Environment(\.presentationMode) var presentationMode
var inputAfterConvertions: Double {
//Use NumberFormatter to read numeric values
let hh = numberFormatter.number(from: height)?.doubleValue ?? 0 //<-
let ww = numberFormatter.number(from: weight)?.doubleValue ?? 0 //<-
var ris: Double = 0
if hh > 0 && ww > 0{
ris = (ww / (hh * hh)) * 10000
return ris
}
return 0
}
var body: some View {
NavigationView{
Form{
Section(header: Text("Enter your height in cm")){
TextField("Input",text: $height)
.keyboardType(.decimalPad)
}
Section(header: Text("Enter your Weight in kg")){
TextField("Input",text: $weight)
.keyboardType(.decimalPad)
}
Section(header: Text("Check result")){
Text("\(inputAfterConvertions as NSNumber, formatter: numberFormatter)") //<-
}
}
.navigationTitle("BMI")
}
}
}
Thank you
Hello
I don't know why but when I put a List before my ForEach loop, all the text disappears
Code:
//
import SwiftUI
struct SearchDetailView: View {
var sf: SF
var body: some View {
ScrollView{
ForEach(sf.items, id: \.self) { item in
HStack{
Image(systemName: item)
Text(item)
}
}
.navigationTitle(sf.title)
}
}
}
Thank you for your time
Hello
I don't get any error when I fetch data but when I run I don't see any data
Thank you
import SwiftUI
import Combine
struct ContentView: View {
		@ObservedObject var networkController = NetworkController()
		@State var search: String = ""
		var body: some View {
				NavigationView{
						Form{
								Section(){
										TextField("Search", text: $search)
								}
								Section(){
										List(networkController.users.filter {
														$0.state.contains(search) }
												 , id: \.state){ user in
												Text(user.state)
										}
								}
						}
						.navigationTitle("API")
				}
		}
}
class NetworkController: ObservableObject {
		private var can: AnyCancellable?
		
		let url = URL(string: "https://api.covidtracking.com/v1/states/current.json")!
		@Published var users = [User(state: "")]
		
		init() {
				self.can = URLSession.shared.dataTaskPublisher(for: url)
						.map { $0.data }
						.decode(type: [User].self, decoder: JSONDecoder())
						.replaceError(with: [])
						.eraseToAnyPublisher()
						.receive(on: DispatchQueue.main)
						.sink(receiveValue: { users in
								self.users	= users
						})
		}
		
}
struct User: Decodable {
		var state: String
}
Hello
When I tap on my TextField more than 2/4 times the app crashes
Before that I get these errors:
2020-12-29 11:28:10.265525+0100 Nums[1670:295112] Can't find keyplane that supports type 4 for keyboard iPhone-PortraitChoco-NumberPad; using 25889PortraitChocoiPhone-Simple-PadDefault
2020-12-29 11:28:18.778004+0100 Nums[1670:295112] Can't find keyplane that supports type 4 for keyboard iPhone-PortraitChoco-NumberPad; using 25889PortraitChocoiPhone-Simple-PadDefault
2020-12-29 11:28:22.268833+0100 Nums[1670:295112] Can't find keyplane that supports type 4 for keyboard iPhone-PortraitChoco-NumberPad; using 25889PortraitChocoiPhone-Simple-Pad_Default
Then after 2/4 four times tapping on the TextField the app crashes and I get this error
2020-12-29 11:28:22.419634+0100 Nums[1670:295112] [error] precondition failure: attribute being read has no value: 768444
AttributeGraph precondition failure: attribute being read has no value: 768444.
(lldb)
Here is the TextField:
GroupBox {
						HStack {
							 TextField("Have a goal?", text: $saveGoal.bound)
									 .keyboardType(.numberPad)
									Spacer()
						Button(action: {
						UserDefaults.standard.set(self.saveGoal, forKey: "Save")																		UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)
																}) {		
																		Text("Save")
																}
												}
										}.padding(.top).padding(.trailing).padding(.leading)
Thank you for your time
Hello
Is there a way to dismiss a decimal Keyboard by tapping (anywhere) on the screen (without putting .onTapGesture {hideKeyboard()} on the NavigationView)
Thank you
Hello
I'm using Measurement(...) to convert watts to femtowatts, but if I convert 1 watts to femtowatts I get 999999999999999.9 instead of 1e+15, I have no idea on how to fix it, any help or ideas, here is the code
:
import SwiftUI
struct PowerView: View {
		
		@State private var inputValue = ""
		
		 let inputUnits = [
				"watts",
				"femtowatts"
		]
		let outputUnits = [
				"watts",
				"femtowatts"
	 ]
		@State private var inputUnitValue = 0
		
		@State private var outputUnitValue = 1
		
		var after: String{
				var input = Measurement(value: 0, unit: UnitPower.watts)
				var output: String = ""
				
				switch inputUnits[inputUnitValue] {
				case "watts": input = Measurement(value: Double(inputValue) ?? 0, unit: UnitPower.watts)
				case "femtowatts": input = Measurement(value: Double(inputValue) ?? 0, unit: UnitPower.femtowatts)
				default: input = Measurement(value: Double(inputValue) ?? 0, unit: UnitPower.watts)
				}
				switch outputUnits[outputUnitValue] {
				case "watts": output = String(describing: input.converted(to: UnitPower.watts))
				case "femtowatts": output = String(describing: input.converted(to: UnitPower.femtowatts))
				default: output = String(describing: input.converted(to: UnitPower.watts))
						
				}
						
				return output
		}
		
				
		var body: some View {
				NavigationView{
						Form{
								Section(header: Text("Enter your Input value")){
												TextField("Have a goal?", text: $inputValue)
								}
								
								Section(header: Text("Input")){
										Picker("Input values", selection: $inputUnitValue){						 	 ForEach(0..<inputUnits.count){ item in
														Text(inputUnits[item])
												}
										}
								}
								
								Section(header: Text("Output")){
										Picker("Output values", selection: $outputUnitValue){
												ForEach(0..<outputUnits.count){ item in
														Text(outputUnits[item])
												}
										}
								}
								
								Section(header: Text("Check your Output value")){
										Text("\(after)")
								}
								
						}
						.navigationBarTitle("Pressure")
				}
		}
		
}
Thank you for your time
(Is there a way to use NumberFormatter with the computed String)
Hello
I'm trying to fetch some data from a JSON Api, but when I access the properties of my struct it tells me Value of Type "Name Of The Struct" has no member "name of the property"
Any idea on how to fix it
Code:
import SwiftUI
import Combine
struct ContentView: View {
		
		@ObservedObject var networkController = NetworkControllerItalia()
		var gridItemLayout = [GridItem(.flexible()), GridItem(.flexible())]
		
		var body: some View {
				NavigationView{
						ScrollView{
								ForEach(networkController.users, id: \.self){ user in
										GroupBox(label: Text(user.round ?? ""), content: {
												VStack{
														Text(user.team1 ?? "")
												}
										}).padding()
						}
						.navigationTitle("Serie A")
				}
		 }
	 }
}
class NetworkControllerItalia: ObservableObject {
		private var can: AnyCancellable?
		
		let url = URL(string: "https://raw.githubusercontent.com/openfootball/football.json/master/2020-21/it.1.json")!
		//let url = URL(string: "google.com")!
		@Published var users = [UserItalia(matches: [])]
		
		init() {
				self.can = URLSession.shared.dataTaskPublisher(for: url)
						.map { $0.data }
						.decode(type: [UserItalia].self, decoder: JSONDecoder())
						//.replaceError(with: [])
						.eraseToAnyPublisher()
						.receive(on: DispatchQueue.main)
						.sink(receiveCompletion: {completion in
								print(completion)
						}, receiveValue: { users in
								self.users	= users
						})
		}
		
}
struct UserItalia: Decodable, Hashable {
		var matches: [Matches]?
}
struct Matches: Decodable, Hashable {
		var round: String?
		var date: String?
		var team1: String?
		var team2: String?
}
Thank You
Hello
Does anyone know how to use real time image recognition in SwiftUI with a Create ML model.
Thank you
Hello
Is there any way to put the 2 Texts in an HStack without putting the 2 ForEachs together?
Code:
ForEach(model.data, id: \.objectID){ obj in
Text(model.getValue(obj: obj))
}.onDelete(perform: model.deleteData)
ForEach(date.data, id: \.objectID){ obj1 in
Text("\(date.getValue(obj: obj1), formatter: dateFormatter)")
}.onDelete(perform: date.deleteData)
Thank you
Hello
How do I solve the Index out of range at line 81
I tried many ways, but none of them worked
//
// ContentView.swift
// Fede
//
// Created by Jad Taljabini on 14/03/21.
//
import SwiftUI
struct ContentView: View {
@State private var media: String = ""
@State private var voto: String = ""
@State private var voti: [Float] = []
@State private var nVoti: Int = 0
@State private var test: String = ""
@State private var voti2: [Float] = []
let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
var body: some View {
NavigationView {
Form {
Section{
TextField("A che media vuoi arrivare", text: $media)
}
Section{
TextField("Quanti voti prenderai", text: $test)
}
Section{
HStack {
TextField("Tuoi voti", text: $voto)
Spacer()
Button(action: {
voti.append(Float(voto) ?? 0)
voto = ""
nVoti = nVoti + 1
}, label: {
Text("Add")
})
}
}
Section{
ForEach(voti, id: \.self){ item in
Text("\(item, specifier: "%.1f")")
}.onDelete(perform: removeRows)
}
Section(header: Text("Voti che devi prendere")){
ForEach(voti2, id: \.self){ item2 in
Text("\(item2)")
}
}
}.onReceive(timer) { input in
voti2 = tutto()
}
.navigationTitle("Media")
}
}
func tutto() - [Float] {
let testInt = Int(test) ?? 0
let mediaFloat = Float(media) ?? 0
var mediaEffettiva = mediaEffFunzione(dim: nVoti)
if mediaEffettiva mediaFloat {
for i in 0..testInt - 2 {
voti2[i] = Float(Int(mediaEffettiva + 1))
}
let mediaEffettivaInt = Int(mediaEffettiva)
let mediaFloatInt = Int(mediaFloat)
var con: Int = 0
while(mediaEffettivaInt mediaFloatInt){
for j in nVoti..nVoti + testInt - 2{
voti[j] = voti2[j - nVoti];
}
mediaEffettiva = mediaEffFunzione(dim: nVoti + testInt)
if(mediaEffettiva mediaFloat){
voti2[con] += 0.5
}
con = con + 1
if con = testInt {
con = 0
}
}
}
return voti2
}
func removeRows(at offsets: IndexSet) {
voti.remove(atOffsets: offsets)
}
func mediaEffFunzione(dim: Int) - Float {
var somma: Float = 0
for i in voti{
somma = somma + i
}
return somma / Float(dim)
}
}
Thank you very much
Hello, Is there a way to use "switch statement" inside of a NavigationLink Destination?
Example:
NavigationLink(destination:
switch i {
case 0: MatematicaView()
case 1: ArteView()
default: EmptyView()
}){
Text("Hello")
}
(The views are different, that's why I don't put them in one struct)
Thank you
Hello
Is there a way to append a number to a Double, like this:
var num: Double = 1
var num2 = num.append(1)
//num2 should be 11
Thank you