7.7 C
London
Monday, October 30, 2023

ios – Swift: Hassle Shuffling Solutions in a Trivia/Quiz App


Hey guys please assist me as I am a newbie in SwiftUI and programming total. That is my first time creating a trivia app. I am encountering a difficulty with shuffled solutions for trivia questions. I am attempting to create a operate that accommodates all of the solutions, together with the right one, and shuffles them randomly however I actually have no idea how to do that. Please assist me, any little assistance is appreciated loads.

That is my code for TriviaAPIData:

import Basis

struct QuestionResponse: Decodable {
   var outcomes: [Question]
}

struct Reply: Identifiable {
   var id = UUID()
   var textual content: String
   var isCorrect: Bool
   
}
       struct Query: Decodable {
           var class: String
           var query: String
           var correctAnswer: String
           var incorrectAnswers: [String]
          
   }

That is my code for TriviaAPI:

import Basis
import SwiftUI

class TriviaAPI: ObservableObject {
    
    struct TriviaAnswer {
        let textual content: String
        let isCorrect: Bool
    }
   
   @Printed var QnAData: [Question] = [] 
    
    func getQnAData(selectedCategoryNumber: Int, selectedDifficultyInPopup: String) async throws {
        
        let endpoint = "https://opentdb.com/api.php?quantity=10&class=(selectedCategoryNumber)&problem=(selectedDifficultyInPopup)&kind=a number of&encode=url3986"
        
        guard let url = URL(string: endpoint) else {throw APIErrors.invalidURL}
        
        var request = URLRequest(url: url)
        
        request.httpMethod = "GET"
        
        request.setValue("utility/json", forHTTPHeaderField: "Content material-Sort")
        
        let (knowledge, response) = strive await URLSession.shared.knowledge(for: request)
        
        guard let response = response as? HTTPURLResponse, response.statusCode == 200 else {
            throw APIErrors.invalidResponse
        }
        
        do {
            let decoder = JSONDecoder()
            decoder.keyDecodingStrategy = .convertFromSnakeCase
            
            let questionResponse = strive decoder.decode(QuestionResponse.self, from: knowledge)
            
            DispatchQueue.principal.sync {
                self.QnAData = questionResponse.outcomes
            }
        } catch {
            throw APIErrors.invalidData
        }
    }
}

Right here is my code for QuizGameScreen:

import Basis
import SwiftUI

struct QuizGameScreen: View {
    
    @StateObject var api = TriviaAPI()
    @Binding var selectedCategoryNumber: Int
    @Binding var selectedCategoryName: String
    @State var currentQuestionIndex = 0
    @Binding var selectedDifficultyInPopup: String
    
    func shuffleAnswers() {
        var correctAnswers = [api.QnAData[currentQuestionIndex].correctAnswer]
        var incorrectAnswers = api.QnAData[currentQuestionIndex].incorrectAnswers
        
        let allAnswers = correctAnswers + incorrectAnswers
        var shuffeldQuestions = allAnswers.shuffled()
    }
    
    var physique: some View {
    
        ZStack{
            
            Picture("NewBgQuizUp")
                .resizable()
                .scaledToFill()
                .edgesIgnoringSafeArea(.all)
                .body(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight:.infinity)
            VStack(alignment: .main){
                Textual content("QuizUp")
                    .font(.system(measurement: 36, design:
                            .rounded)).fontWeight(.daring)
                    .foregroundColor(.white)
                    .offset(x: -100, y: -350)
            }
            Textual content("1 out of 0")
                .font(.system(measurement: 23, design:
                        .rounded)).fontWeight(.daring)
                .foregroundColor(.white)
                .offset(x: 100, y: -300)
            
            VStack{
            
                if !api.QnAData.isEmpty {
                    if currentQuestionIndex < api.QnAData.depend { // Verify if the present query index is inside bounds
                        if let decodedQuestion = api.QnAData[currentQuestionIndex].query.removingPercentEncoding {
                            Textual content(decodedQuestion)
                                .font(.system(measurement: 23, design: .rounded)).fontWeight(.daring)
                                .foregroundColor(.white)
                                .offset(y: -100)
                        } else {
                            Textual content("Did not decode query")
                                .font(.system(measurement: 23, design: .rounded)).fontWeight(.daring)
                                .foregroundColor(.white)
                                .offset(y: -100)
                        }

                        ForEach(0..<api.QnAData[currentQuestionIndex].incorrectAnswers.depend, id: .self) { index in
                            if index < api.QnAData[currentQuestionIndex].incorrectAnswers.depend { // Verify if the index is inside bounds
                                if let decodedAnswer = api.QnAData[currentQuestionIndex].incorrectAnswers[index].removingPercentEncoding {
                                    Button(motion: {
                                       
                                        print("incorrect reply")
                                       
                                    }) {
                                        Textual content(decodedAnswer)
                                            .font(.system(measurement: 20, design: .rounded))
                                            .foregroundColor(.purple)
                                            .body(width: 300, alignment: .main)
                                            .padding()
                                            .background(Shade.white)
                                            .fontWeight(.daring)
                                            .cornerRadius(10)
                                    }
                                }
                            }
                        }
                     if currentQuestionIndex < api.QnAData.depend { 
                            if let decodedCorrectAnswer = api.QnAData[currentQuestionIndex].correctAnswer.removingPercentEncoding {
                                Button(motion: {
                                    print("appropriate reply")
                                }) {
                                    Textual content(decodedCorrectAnswer)
                                        .font(.system(measurement: 20, design: .rounded))
                                        .foregroundColor(.purple)
                                        .body(width: 300, alignment: .main)
                                        .padding()
                                        .background(Shade.white)
                                        .fontWeight(.daring)
                                        .cornerRadius(10)
                                }
                            }
                        }
                    }
                } else {
                    Textual content("Loading...")
                        .font(.system(measurement: 23, design: .rounded)).fontWeight(.daring)
                        .foregroundColor(.white)
                        .offset(y: -100)
                }
            }
        }.job {
                         
            do {
                strive await api.getQnAData(selectedCategoryNumber: selectedCategoryNumber, selectedDifficultyInPopup: selectedDifficultyInPopup)
                shuffleAnswers() // calling on my operate
            } catch APIErrors.invalidData {
                print("Invalid Knowledge")
            } catch APIErrors.invalidURL {
                print("Invalid Url")
            } catch APIErrors.invalidResponse {
                print("Invalid Response")
            } catch {
                print("Common error")
            }
        }
    }
}
struct QuizGameScreen_Previews: PreviewProvider {
    static var previews: some View {
        QuizGameScreen(selectedCategoryNumber: .fixed(21), selectedCategoryName: .fixed("Sport"), selectedDifficultyInPopup: .fixed("Simple"))
    }
}
enum APIErrors: Error {
    case invalidURL
    case invalidResponse
    case invalidData
}

Latest news
Related news

LEAVE A REPLY

Please enter your comment!
Please enter your name here