Creating a Questionnaire iPhone App with SQLite: A Step-by-Step Guide

Building a Questionnaire iPhone App with SQLite

In this tutorial, we will guide you through the process of creating a simple questionnaire iPhone app that stores questions in an SQLite database. We will cover the basics of SQLite, how to set up the database, and how to implement the logic for the questionnaire.

Table of Contents

Introduction

What is SQLite?

SQLite is a self-contained, file-based relational database that can be embedded into an application. It was designed to be lightweight and easy to use, making it a popular choice for mobile app development.

Why Use SQLite for iPhone Apps?

SQLite offers several advantages for iPhone app development:

  • Lightweight: SQLite databases are relatively small compared to other database management systems.
  • Self-contained: The entire database is stored in a single file, eliminating the need for server-side storage or complex networking protocols.
  • Easy to use: SQLite provides an SQL interface that is easy to learn and use, even for developers without extensive database experience.

Setting Up the Database

Creating a New Database

To start working with SQLite in your iPhone app, you’ll need to create a new database. You can do this using the FMDB library, which wraps around SQLite and provides a convenient API for interacting with the database.

#import <FMDB/FMDB.h>

// Create a new instance of the database
 FMDB *db = [[FMDB alloc] initWithPath:@"questionnaire.db"];

// Check if the database was created successfully
if ([db open]) {
    NSLog(@"Database opened successfully!");
} else {
    NSLog(@"Failed to open database.");
}

Designing the Table Structure

The table structure will depend on your specific requirements, but for a basic questionnaire app, you’ll need to store questions and answers. Here’s an example of what this might look like:

CREATE TABLE questions (
    id INTEGER PRIMARY KEY,
    question TEXT NOT NULL,
    answer1 TEXT NOT NULL,
    answer2 TEXT NOT NULL,
    answer3 TEXT NOT NULL,
    answer4 TEXT NOT NULL,
    correct_answer INTEGER NOT NULL,
    did_answer_correct INTEGER NOT NULL
);

Inserting Sample Data

To test your database, you can insert some sample data using SQL:

// Insert a new question with sample answers
 NSString *sql = @"INSERT INTO questions (question, answer1, answer2, answer3, answer4, correct_answer, did_answer_correct) VALUES ('What is the capital of France?', 'Paris', 'Lyon', 'Marseille', 'Nice', 1, 0);";
[db execute:sql];

// Insert another question with sample answers
sql = @"INSERT INTO questions (question, answer1, answer2, answer3, answer4, correct_answer, did_answer_correct) VALUES ('What is the largest planet in our solar system?', 'Jupiter', 'Saturn', 'Mars', 'Earth', 0, 0);";
[db execute:sql];

Implementing the Questionnaire Logic

Defining the Question Class

To represent individual questions, you can create a custom Question class:

#import <Foundation/Foundation.h>

@interface Question : NSObject

@property (nonatomic) NSString *question;
@property (nonatomic) NSArray *answers;

@end

@implementation Question

- (instancetype)initWithQuestion:(NSString *)question answers:(NSArray *)answers {
    self = [super init];
    if (self) {
        _question = question;
        _answers = answers;
    }
    return self;
}

@end

Creating a Questionnaire Controller

To manage the flow of questions and user input, you can create a custom QuestionnaireController class:

#import <UIKit/UIKit.h>
#import "Question.h"

@interface QuestionnaireController : UIViewController

@property (nonatomic) NSArray *questions;

@end

@implementation QuestionnaireController

- (instancetype)initWithQuestions:(NSArray *)questions {
    self = [super init];
    if (self) {
        _questions = questions;
    }
    return self;
}

@end

Handling User Input and Updating the Database

When a user selects an answer, you’ll need to check their response against the correct answer stored in the database. Here’s an example of how this might look:

#import <UIKit/UIKit.h>
#import "Question.h"

@interface QuestionViewController : UIViewController

@property (nonatomic) Question *question;

@end

@implementation QuestionViewController

- (instancetype)initWithQuestion:(Question *)question {
    self = [super init];
    if (self) {
        _question = question;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];

    // Display the question and answers
    for (NSString *answer in self.question.answers) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.titleLabel.text = answer;
        button.backgroundColor = [UIColor greenColor]; // Assume this is the correct answer
        [button addTarget:self action:@selector(answerSelected:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:button];
    }
}

- (void)answerSelected:(UIButton *)button {
    // Get the selected answer and compare it to the correct answer
    NSString *selectedAnswer = button.titleLabel.text;
    BOOL isCorrect = [selectedAnswer isEqualToString:self.question.answers[0]];

    // Update the database with the user's response
    NSLog(@"Correct: %d", isCorrect);

    // Navigate to the next question or display a result message
}

Testing and Debugging the App

To test your app, you’ll need to create sample data and use it in your questions. Here’s an example of how this might look:

// Create a new array of questions with sample answers
NSArray *questions = @[
    [[Question alloc] initWithQuestion:@"What is the capital of France?" answers:@[@"Paris", @"Lyon", @"Marseille", @"Nice"]],
    [[Question alloc] initWithQuestion:@"What is the largest planet in our solar system?" answers:@[@"Jupiter", @"Saturn", @"Mars", @"Earth"]]
];

// Create an instance of the QuestionnaireController
QuestionnaireController *controller = [[QuestionnaireController alloc] initWithQuestions:questions];

This code provides a basic example of how you might implement a questionnaire app with user input and database storage. Of course, this is just a starting point, and there are many ways you could customize and extend this code to suit your specific needs.

You can also use CocoaPods to make the development process smoother by adding some dependencies to your project:

// Add the following lines to your Podfile:
pod 'FMDB'

Then run pod install in your terminal to get the pods into your project.

Note that this is a simplified example and does not cover all possible edge cases or features. Depending on your requirements, you might need to add more functionality, error handling, or testing code.


Last modified on 2024-06-26