runtime error when try to read fetchrequest<> - swift

I want to get data form coredata ,and show it in Charts,
there is a runtime error at the code in init func when app is loaded:
let x=self.marks.wrappedValue.count
the error message is :Thread 1: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)
the whole code is following:
import SwiftUI
import Charts
import CoreData
struct CareDetails: View {
#Environment(\.managedObjectContext) var context
let timeSpan=["day","week","month","year"]
let care:Care
var marks:FetchRequest<Mark>
#State private var timeSpanIndex = 0
#State private var showSheet = false
private var sessions:[Int]=[]
private var accuracy:[Double]=[]
init(care:Care){
self.care=care
self.marks = FetchRequest(entity:Mark.entity(),
sortDescriptors: [],
predicate: NSPredicate(format:"care_id == %#",care.id!.uuidString))
let x=self.marks.wrappedValue.count
}
var body: some View {
VStack{
Picker(selection: $timeSpanIndex, label: Text("timeSpan")) {
ForEach(0..<timeSpan.count,id:\.self){ idx in
Text(self.timeSpan[idx])
}
}
.pickerStyle(SegmentedPickerStyle())
.padding()
LineChartViewSwiftUI(dataLabel: self.care.unit!,sessions: self.sessions,accuracy: self.accuracy)
Form{
Section{
List{
NavigationLink(destination:
CareDetailsList(marks: self.marks)
.environment(\.managedObjectContext, self.context)
){
Text("显示所有数据")
}
}
}
.multilineTextAlignment(.leading)
}
.padding()
}
}
}

It hasn't been evaluated yet. It resolves when update() gets called by your view's body function. Try structuring it slightly differently and using it directly in body.
struct CareView: View {
let care: Care
#FetchRequest var marks: FetchedResult<Mark>
#State private var timeSpanIndex = 0
#State private var showSheet = false
init(care: Care) {
self.care = care
self._marks = FetchRequest(...) // set up as before now. note the `_` though!
}
var body: some View {
// make sure you can ID each `Mark` by something
ForEach(marks, id: \.id) { mark in
// create your `MarkView` here
}
}
}

Related

SwiftUI: Why do I get the same pattern of random items in an array?

I'm working on my project and there's a section where you can test yourself on Japanese letters. You tap a button that plays a sound of a letter then you choose the right button out of three with the correct letter. there are 10 questions in total and it should always randomize, the letters but whenever you come back to the view, the first question is always the same. after the first one it randomizes the rest of the questions but the first question always has the same pattern of letters. What I want is getting a random pattern of letters for the first question every time you come back to the view. I'd appreciate any help.
here's the code of QuestionView:
import SwiftUI
struct HiraganaQuiz: View {
var hiraganas: [Japanese] = Bundle.main.decode("Hiragana.json")
#State private var correctAnswer = Int.random(in: 0...45)
#StateObject var soundplayer = Audio()
#State private var answer = ""
#State private var counter = 0
#State private var correctAnswerCounter = 0
#State private var showingAlert = false
#State private var alertMessage = ""
#State private var disabled = false
var body: some View {
ZStack {
Color.darkBackground
.ignoresSafeArea()
VStack {
Text("\(counter) / 10")
.padding(.top,40)
.foregroundColor(.white)
.font(.system(size:30).bold())
Text("Tap the speaker and choose the right letter")
Button {
soundplayer.playSounds(file: hiraganas[correctAnswer].voice1)
} label: {
Image(systemName: "speaker.wave.3.fill")
}
.font(.system(size:70))
height: 110)
HStack {
ForEach (0...2, id: \.self) { index in
Button {
letterTapped(index)
} label: {
Text(hiraganas[index].letter)
}
}
.disabled(disabe())
.foregroundColor(.white)
.font(.system(size: 35).bold())
Text("\(answer)")
.foregroundColor(.white)
.padding(.bottom,20)
.font(.system(size: 30))
Button {
resetTheGame()
} label: {
Text("Next")
}.buttonStyle(.plain)
.font(.system(size: 30).bold())
.frame(width: 200, height: 50)
}
}
.alert("⭐️ Well done ⭐️", isPresented: $showingAlert) {
Button("Retry", action: reset)
} message: {
Text(alertMessage)
}
} .onAppear { hiraganas = Bundle.main.decode("Hiragana.json").shuffled() }
}
I'm surprised this even compiles -- it should be giving you an error about trying to initialize state like this.
Instead, you can shuffle in the properties in the property initializer:
struct HiraganaQuiz: View {
#State private var hiraganas: [Japanese] = Bundle.main.decode("Hiragana.json").shuffled()
Update, to show the request for onAppear usage:
struct HiraganaQuiz: View {
#State private var hiraganas: [Japanese] = []
var body: some View {
ZStack {
// body content
}.onAppear {
hiraganas = Bundle.main.decode("Hiragana.json").shuffled()
}
}
}

SwiftUI: Pass an ObservableObject's property into another class's initializer

How do I pass a property from an ObservedObject in a View, to another class's initializer in the same View? I get an error with my ObservedObject:
Cannot use instance member 'project' within property initializer; property initializers run before 'self' is available
The reason I want to do this is I have a class which has properties that depend on a value from the ObservedObject.
For example, I have an ObservedObject called project. I want to use the property, project.totalWordsWritten, to change the session class's property, session.totalWordCountWithSession:
struct SessionView: View {
#Binding var isPresented: Bool
#ObservedObject var project: Project
// How to pass in project.totalWordsWritten from ObservedObject project to totalWordCount?
#StateObject var session:Session = Session(startDate: Date(), sessionWordCount: 300, totalWordCount: 4000)
var body: some View {
NavigationView {
VStack(alignment: .leading) {
Form {
Section {
Text("Count")
HStack {
Text("Session word count")
TextField("", value: $session.sessionWordCount, formatter: NumberFormatter())
.textFieldStyle(.roundedBorder)
}
HStack {
// Changing text field here should change the session count above
Text("Total word count")
TextField("", value: $session.totalWordCountWithSession, formatter: NumberFormatter())
.textFieldStyle(.roundedBorder)
}
}
}
}.toolbar {
ToolbarItem(placement: .navigationBarTrailing) {
Button("Save") {
// Save this session into the project
project.addSession(newSession: session)
isPresented = false
}
}
}
}
}
}
struct SessionView_Previews: PreviewProvider {
static var previews: some View {
SessionView(isPresented: .constant(true), project: Project(title: "TestProject", startWordCount: 0))
}
}
Below is the rest of the example:
HomeView.swift
import SwiftUI
struct HomeView: View {
#State private var showingSessionPopover:Bool = false
#StateObject var projectItem:Project = Project(title: "Test Project", startWordCount: 4000)
var body: some View {
NavigationView {
VStack(alignment: .leading) {
Text(projectItem.title).font(Font.custom("OpenSans-Regular", size: 18))
.fontWeight(.bold)
Text("Count today: \(projectItem.wordsWrittenToday)")
Text("Total: \(projectItem.totalWordsWritten)")
}
.toolbar {
ToolbarItem {
Button(action: {
showingSessionPopover = true
}, label: {
Image(systemName: "calendar").imageScale(.large)
}
)
}
}
}.popover(isPresented: $showingSessionPopover) {
SessionView(isPresented: $showingSessionPopover, project: projectItem)
}
}
}
Session.swift:
import Foundation
import SwiftUI
class Session: Identifiable, ObservableObject {
init(startDate:Date, sessionWordCount:Int, totalWordCount: Int) {
self.startDate = startDate
self.endDate = Calendar.current.date(byAdding: .minute, value: 30, to: startDate) ?? Date()
self.sessionWordCount = sessionWordCount
self.totalWordCount = totalWordCount
self.totalWordCountWithSession = self.totalWordCount + sessionWordCount
}
var id: UUID = UUID()
#Published var startDate:Date
#Published var endDate:Date
var totalWordCount: Int
var sessionWordCount:Int
#Published var totalWordCountWithSession:Int {
didSet {
sessionWordCount = totalWordCountWithSession - totalWordCount
}
}
}
Project.swift
import SwiftUI
class Project: Identifiable, ObservableObject {
var id: UUID = UUID()
#Published var title:String
var sessions:[Session] = []
#Published var wordsWrittenToday:Int = 0
#Published var totalWordsWritten:Int = 0
#Published var startWordCount:Int
init(title:String,startWordCount:Int) {
self.title = title
self.startWordCount = startWordCount
self.calculateDailyAndTotalWritten()
}
// Create a new session
func addSession(newSession:Session) {
sessions.append(newSession)
calculateDailyAndTotalWritten()
}
// Re-calculate how many
// today and in total for the project
func calculateDailyAndTotalWritten() {
wordsWrittenToday = 0
totalWordsWritten = startWordCount
for session in sessions {
if (Calendar.current.isDateInToday(session.startDate)) {
wordsWrittenToday += session.sessionWordCount
}
totalWordsWritten += session.sessionWordCount
}
}
}
You can use the StateObject initializer in init:
struct SessionView: View {
#Binding var isPresented: Bool
#ObservedObject var project: Project
#StateObject var session:Session = Session(startDate: Date(), sessionWordCount: 300, totalWordCount: 4000)
init(isPresented: Binding<Bool>, project: Project, session: Session) {
_isPresented = isPresented
_session = StateObject(wrappedValue: Session(startDate: Date(), sessionWordCount: 300, totalWordCount: project.totalWordsWritten))
self.project = project
}
var body: some View {
Text("Hello, world")
}
}
Note that the documentation says:
You don’t call this initializer directly
But, it has been confirmed by SwiftUI engineers in WWDC labs that this is a legitimate technique. What runs in wrappedValue is an autoclosure and only runs on the first init of StateObject, so you don't have to be concerned that every time your View updates that it will run.
In general, though, it's a good idea to try to avoid doing things in the View's init. You could consider instead, for example, using something like task or onAppear to set the value and just put a placeholder value in at first.

SwiftUI: How to retrieve data from Firestore in second view?

This is my first SwiftUI project and am very new in programming.
I have a View Model and a picker for my Content View, manage to send $selection to Detail View but not sure how to get it to read from the Firestore again. I kinda feel like something is missing, like I need to use an if-else, but can't pinpoint exactly what is the problem. Searched through the forum here but can't seemed to find a solution.
Here is the VM
import Foundation
import Firebase
class FoodViewModel: ObservableObject {
#Published var datas = [Food]()
private var db = Firestore.firestore()
func fetchData(){
db.collection("meals").addSnapshotListener { (snap, err) in
DispatchQueue.main.async {
if err != nil {
print((err?.localizedDescription)!)
return
} else {
for i in snap!.documentChanges{
let id = i.document.documentID
let name = i.document.get("name") as? String ?? ""
let weight = i.document.get("weight") as? Int ?? 0
let temp = i.document.get("temp") as? Int ?? 0
let time = i.document.get("time") as? Int ?? 0
self.datas.append(Food(id: id, name: name, weight: weight, temp: temp, time: time))
}
}
}
}
}
}
struct ContentView: View {
#ObservedObject var foodDatas = FoodViewModel()
#State private var id = ""
#State public var selection: Int = 0
var body: some View {
NavigationView{
let allFood = self.foodDatas.datas
ZStack {
Color("brandBlue")
.edgesIgnoringSafeArea(.all)
VStack {
Picker(selection: $selection, label: Text("Select your food")) {
ForEach(allFood.indices, id:\.self) { index in
Text(allFood[index].name.capitalized).tag(index)
}
}
.onAppear() {
self.foodDatas.fetchData()
}
Spacer()
NavigationLink(
destination: DetailView(selection: self.$selection),
label: {
Text("Let's make this!")
.font(.system(size: 20))
.fontWeight(.bold)
.foregroundColor(Color.black)
.padding(12)
})
}
And after the picker selected a food type, I hope for it to display the rest of details such as cooking time and temperature. Now it is displaying 'index out of range' for the Text part.
import SwiftUI
import Firebase
struct DetailView: View {
#ObservedObject var foodDatas = FoodViewModel()
#Binding var selection: Int
var body: some View {
NavigationView{
let allFood = self.foodDatas.datas
ZStack {
Color("brandBlue")
.edgesIgnoringSafeArea(.all)
VStack {
Text("Cooking Time: \(allFood[selection].time) mins")
}
}
}
}
Appreciate for all the help that I can get.
In your DetailView, you're creating a new instance of FoodViewModel:
#ObservedObject var foodDatas = FoodViewModel()
That new instance has not fetched any data, and thus the index of the selection is out of bounds, because its array is empty.
You could pass your original ContentView's copy of the FoodDataModel as a parameter.
So, the previous line I quoted would become:
#ObservedObject var foodDatas : FoodViewModel
And then your NavigationLink would look like this:
NavigationLink(destination: DetailView(foodDatas: foodDatas, selection: self.$selection) //... etc

SwiftUI SceneDelegate - contentView Missing argument for parameter 'index' in call

I am trying to create a list using ForEach and NavigationLink of an array of data.
I believe my code (see the end of the post) is correct but my build fails due to
"Missing argument for parameter 'index' in call" and takes me to SceneDelegate.swift a place I haven't had to venture before.
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
I can get the code to run if I amend to;
let contentView = ContentView(habits: HabitsList(), index: 1)
but then all my links hold the same data, which makes sense since I am naming the index position.
I have tried, index: self.index (which is what I am using in my NavigationLink) and get a different error message - Cannot convert value of type '(Any) -> Int' to expected argument type 'Int'
Below are snippets of my code for reference;
struct HabitItem: Identifiable, Codable {
let id = UUID()
let name: String
let description: String
let amount: Int
}
class HabitsList: ObservableObject {
#Published var items = [HabitItem]()
}
struct ContentView: View {
#ObservedObject var habits = HabitsList()
#State private var showingAddHabit = false
var index: Int
var body: some View {
NavigationView {
List {
ForEach(habits.items) { item in
NavigationLink(destination: HabitDetail(habits: self.habits, index: self.index)) {
HStack {
VStack(alignment: .leading) {
Text(item.name)
.font(.headline)
Text(item.description)
}
}
}
}
}
}
}
}
struct HabitDetail: View {
#Environment(\.presentationMode) var presentationMode
#ObservedObject var habits: HabitsList
var index: Int
var body: some View {
NavigationView {
Form {
Text(self.habits.items[index].name)
}
}
}
}
You probably don't need to pass the whole ObservedObject to the HabitDetail.
Passing just a HabitItem should be enough:
struct HabitDetail: View {
#Environment(\.presentationMode) var presentationMode
let item: HabitItem
var body: some View {
// remove `NavigationView` form the detail view
Form {
Text(item.name)
}
}
}
Then you can modify your ContentView:
struct ContentView: View {
#ObservedObject var habits = HabitsList()
#State private var showingAddHabit = false
var body: some View {
NavigationView {
List {
// for every item in habits create a `linkView`
ForEach(habits.items, id:\.id) { item in
self.linkView(item: item)
}
}
}
}
// extract to another function for clarity
func linkView(item: HabitItem) -> some View {
// pass just a `HabitItem` to the `HabitDetail`
NavigationLink(destination: HabitDetail(item: item)) {
HStack {
VStack(alignment: .leading) {
Text(item.name)
.font(.headline)
Text(item.description)
}
}
}
}
}

How do I change the bool value of an item that comes from a struct and hence update a checklist?

Background
I am trying to build a list with a checkmark/tick box next to it. A struct is used to create the "data" for each item. This is then passed on to a class which holds an array of the items created by the struct. From here I used the observable object protocol and passed the class into a list.
Objective
I would like to be able to individually mark each item as completed when it is done.
Current Analysis
I know the image switches when I manually change the 'completed' value from false to true.
I also tested the onTapAction just to be sure it is working.
I think the problem lies in "self.one.completed.toggle()" or the binding or something I am unaware of.
struct One: Identifiable, Codable {
let id = UUID()
var item: String
var completed:Bool = false
}
class OneList: ObservableObject{
#Published var items1 = [One]()
struct ContentView: View {
#ObservedObject var itemss1 = OneList()
#ObservedObject var itemss2 = TwoList()
#ObservedObject var itemss3 = ThreeList()
#ObservedObject var itemss4 = FourList()
#State private var showingAdditem: Bool = false
#Binding var one:One
var body: some View {
NavigationView{
ZStack{
List{
Section(header: Text("Vital")){
ForEach(itemss1.items1){ item in
HStack{
Image(systemName: self.one.completed ? "checkmark.circle":"circle")
.onTapGesture {
self.one.completed.toggle()
}
Text(item.item)}
P.S. I am relatively new to Swift and Stack overflow so any other suggestions would be appreciated
In my other answer I achieved something like this with ObservableObject protocol for needed object and then playing with EnvironmentObject. Actually I didn't try to do this with other wrappers. Here is the code, where you can see switching images:
import SwiftUI
class One: Identifiable, ObservableObject { // ObservableObject requires class
let id: UUID
var item: String = "[undefined]"
#Published var completed: Bool = false // this will affect the UI
init(item: String, completed: Bool) {
id = UUID()
self.item = item
self.completed = completed
}
}
class OneList: ObservableObject{
#Published var items = [One(item: "first", completed: false),
One(item: "second", completed: false),
One(item: "third", completed: false)]
}
struct CheckboxList: View {
#EnvironmentObject var itemList: OneList
var body: some View {
List {
Section(header: Text("Vital")) {
ForEach(itemList.items.indices) { index in
VitalRow()
.environmentObject(self.itemList.items[index])
.onTapGesture {
self.itemList.items[index].completed.toggle()
}
}
}
}
}
}
struct VitalRow: View {
#EnvironmentObject var item: One
var body: some View {
HStack{
Image(systemName: item.completed ? "checkmark.circle" : "circle")
Text("\(item.item)")
}
}
}
struct CheckboxList_Previews: PreviewProvider {
static var previews: some View {
CheckboxList().environmentObject(OneList())
}
}