ios – How to get the latest date when the game is played in Swift


Hi I am making an quiz app with Swift and I have been struggling to display the day when the game is played. I am trying to get the data in checkGameEnded by using insert() but I have not succeeded yet (playerScore can be displayed without any problem). That would be really appreciated if you could give me an assistance. Thank you.

View1
struct PlayGameView: View {
    
    @State private var date: Date = .now
    var body: some View {
       The codes to play the game here 
}

func checkGameEnded() {
        // finish the game once all words in the array have been used
        if usedMoves.count == maxNumQuestion || numberOfLeftWords == 0 {
            // move to ResultView view
            isGameEnded = true
            
            let playerItem = PlayerItem(playerScore: playerScore, date: date)
            context.insert(playerItem)
        }
    }

View2 
struct ContentView: View {
      @Environment(\.modelContext) var context
      @Query(sort: [SortDescriptor(\PlayerItem.playerScore, order:   .reverse),SortDescriptor(\PlayerItem.date, order: .reverse)]) var playerItems: [PlayerItem]

var body: some View {
                    // get the highest score 
                    Text("Your best score : \(playerItems.first?.playerScore ?? 0)")
                        .foregroundStyle(.white)
                        .bold()
                        .font(.title2)
                        .offset(x:-10)
                        .padding(.bottom,40)
                    
                    // get the latest day when the game is play (this has an issue) 
                    if let firstItem = playerItems.first {
                        Text("\(firstItem.date)")
                            .foregroundStyle(.white)
                            .bold()
                            .font(.title2)
                            .padding(.bottom,40)
                    } else {
                        Text("Let's study!")
                            .foregroundStyle(.white)
                            .bold()
                            .font(.title2)
                            .padding(.bottom,40)
                    }
}
                        

I have been following the tutorial on YouTube.

Latest articles

spot_imgspot_img

Related articles

Leave a reply

Please enter your comment!
Please enter your name here

spot_imgspot_img