0% found this document useful (0 votes)
9 views

Final Report (1) (1) (1)

Uploaded by

VISHNU Sain
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Final Report (1) (1) (1)

Uploaded by

VISHNU Sain
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

INFORMATICS & COMPUTATIONAL SCIENCES

UNIVERSITY COLLEGE OF SCIENCE


MOHANLAL SUKHADIA UNIVERSITY
(NAAC Accredited 'A' Grade University)

VIGYAN BHAWAN BLOCK-A

BCA 6th SEMESTER

(Session- 2023-24)
Batch-C

...Chat application…

A
project report
submitted
in partial fulfilment
for the award of the Degree of
Bachelor of Computer Applications
Department of IT&CS

Submitted To : Submitted By:


Dr. Avinash Panwar Vishnu Sain
Enrollment No. - 217665620

i
Candidate’s Declaration

I hereby declare that the work, which is being presented in the project, entitled
Chat Application in partial fulfillment for the award of Degree of Bachelor of
Computer Application in Dept. of DEPARTMENT OF IT & CS and submitted to the
Department of BCA , UNIVERSITY COLLEGE OF SCIENCE
Mohanlal Sukhadia University is a record of my own investigations carried under the
Guidance of Dr.AVINASH PANWAR , DEPARTMENT OF IT & CS .

I have not submitted the matter presented in this report anywhere for the award of any other Degree.

Vishnu Sain
IOS APPLICATION DEVLOPMENT
Enrollment No. : 217665620

NAME OF COLLEGE: UNIVERSITY COLLEGE OF SCIENCE, UDAIPUR(RAJ.)

Counter Signed by:


Mahesh Choudhary
(Co Founder MATE)

i
CERTIFICATE

This is to certify that Vishnu Sain of Semester VI B.C.A. 2023-24 has presented a
major project titled Chat Application in partial fulfillment for the award of the
degree of Bachelor of Computer Application ,

Mohanlal Sukhadia University, Udaipur(Rajasthan).

The contents of this report do not form a basis for the award of any previous
degree to the above mentioned, or to anyone else , to the best of our knowledge.
The software is working perfectly and work is appreciable. We find the quality of
the work presented according to our level of satisfaction.

Date: September,2024

Ramesh Ameta Mahesh Choudhary


Project Co-ordinator Supervisor

ii
ACKNOWLEDGEMENT

The satisfaction that accompanies that the successful completion of any task would
be incomplete without the mention of people whom case less cooperation made it
possible, whom constant guidance and encouragement crown all efforts with
success.

So I am fortunate to find opportunity to express my deep sense of gratitude and


sincere thanks to all those people who helped me with the guidance and assistance.
Their contribution has been invaluable.

First of all, 1 am thankful to "MOHANLAL SUKHADIA UNIVERSITY" for


keeping this Project in curriculum, which provides real world experience before
degree completion

By being the student of Mohanlal Sukhadia University, Udaipur, 1 convey a


sincere thanks to Dr. Avinash Panwar, for providing all the facilities required for
making the project successful.

I would also like to thank all the faculty members and friends of Mohanlal
Sukhadia University, Udaipur, for their hard work, support and inspiration
provided by them during the duration of the B.C.A degree. Their guidance was
always fruitful.

VISHNU SAIN

iii
ABSTRACT

This project involves the development of a feature-rich Chat application specifically for a Chat,
utilizing Swift for the iOS application development and Firebase for backend services. The primary
goal of the project is to provide a seamless and intuitive talking for users, encompassing
functionalities such as random chat and also send images to each other.

Key Features for the Chat Application:

1. User Interface:

1. SwiftUI-based UI: Retain the clean, user-friendly interface but change the focus to support
chat functionality.
2. Room List: Display a list of chat rooms that users can join or create.
3. Chat Room Interface: A messaging interface that allows users to see messages and images
shared in real-time.
4. Tab Bars for Navigation: Tabs for switching between chats, contacts, and profile.

2. Chat Rooms:

1. Create and Join Rooms: Users can create chat rooms, either public or private, and invite
others.
2. Room List: Fetch and display available rooms from Firebase Firestore, categorized by
random groups or user-specific groups.
3. Real-Time Updates: Rooms update automatically with new messages using Firebase’s real-
time features.

3. Messaging Functionality:

1. Text Messages: Users can send and receive text messages in real-time.
2. Image Sharing: Allow users to upload and share images in chats using Firebase Cloud
Storage.
3. Message Status: Show if a message has been sent, delivered, or read.

4. Group Chat:

1. Multiple Participants: Support for multiple users in a room.


2. Message Synchronization: Real-time message synchronization using Firebase to ensure
everyone sees the same conversation.
3. Notifications: Push notifications for new messages, including mentions or direct messages
within groups.

5. User Authentication:

1. Firebase Authentication: Users can sign in with email, Google, or Apple ID, keeping the
secure login functionality from the e-commerce app.
2. Profile Management: Allow users to update profiles and manage their chat settings.

1
6. Backend Integration:

1. Firebase Firestore: Store chat rooms, messages, and user data for real-time syncing across
all devices.
2. Cloud Storage: Store and retrieve images shared within chat rooms.
3. Firebase Functions: Can be used for sending notifications or processing messages (e.g.,
moderation).

Steps to Convert:

Redesign UI for Chat Functionality:

1. Convert the product catalog view into a room list, where users can browse available chat
rooms.
2. Replace product detail pages with chat room interfaces.

Modify Data Structure:

1. Adjust the Firestore data model from products and carts to rooms and messages.
2. Use collections for rooms, and store messages as subcollections of each room.

Implement Group Chat Logic:

1. Use Firebase Firestore’s real-time capabilities to manage group chats, ensuring messages
appear instantly for all participants.
2. Integrate image uploading functionality through Firebase Storage, allowing users to share
images within the room.

Real-Time Communication:

1. Ensure real-time synchronization of messages and images using Firebase's real-time database
features or Firestore.

2
CONTENTS

Candidate’s Declaration ........................................................................................................ i


Certificate ............................................................................................................................ ii
Acknowledgement .............................................................................................................. iii
Abstract............................................................................................................................. iv-v
List of Figures ..................................................................................................................... 2
List of Tables ..................................................................................................................... 4

Chapter 1: Introduction ................................................................................................ 7-10


1.1 Aim
1.2 Objective

Chapter 2: SDLC Steps ................................................................................................ 11-13


2.1 Planning and Requirement Analysis
2.2 System Design
2.3 Implementation
2.4 Testing
2.5 Deployment
2.6 Maintenance and Support
2.7 Documentation

Chapter 3: Requirement Specification ......................................................................... 14


3.1 Software Requirement
3.2 Hardware Requirement

Chapter 4: Technology Used ....................................................................................... 15-19


4.1 Frontend-Backend Technology
4.1.1 Swift
4.2 Database Technology
4.2.1 Firebase
4.3 Tools Required
4.3.11 Xcode 15

3
Chapter 5: Project Design ........................................................................................... 20-22
5.1 E-R Diagram
5.2 DFD Diagram
5.2.1 Level-0 DFD Diagram
5.2.2 Level-1 DFD Diagram
1.1.1 Level-2 DFD Diagram

Chapter 6: Snapshots .................................................................................................. 23-37


6.1 Frontend Snapshots
6.1.1 Register Page
6.1.2 Login Page
6.1.3 Home Page
6.1.4 Room Creation Page
6.1.5 Room Deletion Page
6.1.6 Chat Page
6.1.7 Send Image Page
6.1.8 Typing Indicator Page
6.1.9 Conversation Page
6.1.10 Conversation Deletion Page
6.1.11 Applicatiion Navigation Setup
6.2 Backend Snapshots
6.2.1 Firebase Table-1
6.2.2 Firebase Table-2
6.2.3 Firebase Table-3
6.2.4 Firebase Table-4

Chapter 7: Testing....................................................................................................... 38-41


7.1 Unit Testing Phase
7.2 Integration Testing Phase
7.3 User Interface Testing Phase
7.4 Performance Testing Phase
7.5 Security Testing Phase
7.6 Usability Testing Phase
7.7 Beta Testing Phase
7.8 Regression Testing Phase

4
Chapter 8: Future Scope Of the Project ..................................................................... 42-43

Chapter 9: Conclusion ...................................................................................................... 44

Chapter 10: Bibliography and References ....................................................................... 45

Project Structure & Coding ............................................................................................ 46-61

5
LIST OF FIGURES

Fig. 2.1 (SDLC Steps) ................................................................................................................10

Fig. 4.1 (Technology Logo) ....................................................................................................... 12

Fig 4.1.1 (Swift Logo) .................................................................................................... 12

Fig 4.2.1 (Firebase Logo) ............................................................................................... 14

Fig 4.3.1 (Xcode Logo) .................................................................................................. 16

Fig 5.1 (E-R Diagram) .................................................................................................... 20

Fig 5.2.1( Level-0 DFD) ................................................................................................. 21

Fig 5.2.2 (Level-1 DFD) ................................................................................................. 21

Fig 5.2.3 (Level-2 DFD) ................................................................................................. 22

Fig 6.1.1 (Register Page) ................................................................................................ 23

Fig 6.1.2 (Login Page) .................................................................................................... 24

Fig 6.1.3 (Home Page).................................................................................................... 25

Fig 6.1.4 (Room Creation Page) ..................................................................................... 26

Fig 6.1.5 (Room Deletion Page) ..................................................................................... 27

Fig 6.1.6 (Chat Page)...................................................................................................... 28

Fig 6.1.7 (Send Image Page)........................................................................................... 29

Fig 6.1.8 (Typing Indicator Page) ................................................................................... 30

Fig 6.1.9 (Conversation Page) ........................................................................................ 31

Fig 6.1.10 (Conversation Deletion Page) ........................................................................ 32

6
Fig 6.2.1 (Firebase Table-1) ........................................................................................... 36

Fig 6.2.2 (Firebase Table-2) ........................................................................................... 36

Fig 6.2.3 (Firebase Table-3) ........................................................................................... 37

Fig 6.2.4 (Firebase Table-4) ........................................................................................... 37

Fig 7.1 (Testing)............................................................................................................. 38

7
LIST OF TABLES

Table 3.1 (Software Requirements)............................................................................................. 14

Table 3.2 (Hardware Requirements) ........................................................................................... 14

8
Chapter 1

INTRODUCTION

In the rapidly advancing world of digital communication, mobile applications have become essential tools
for fostering connections and facilitating real-time interactions. This project focuses on the development of a
sophisticated Acrobat Chat Application, leveraging the robust capabilities of Xcode and Swift, and utilizing
Firebase for backend services.

The primary objective of this endeavor is to revolutionize the way users engage in group conversations,
providing them with a seamless, dynamic, and intuitive platform for communication. By harnessing the
power of mobile technology, the application aims to not only meet but exceed the expectations of modern
users who demand convenience, personalization, and a smooth user experience. Beyond merely facilitating
group chats, the Room Chat Application aspires to immerse users in a real-time communication environment,
where they can create rooms, chat in groups, and share images effortlessly.

At its core, this project is driven by a commitment to enhance user interaction and engagement within chat
rooms. Through intuitive design and advanced functionalities, the application will cater to diverse user
preferences, ensuring accessibility across various iOS devices. It promises to deliver a visually appealing
interface while offering streamlined navigation, responsive design, and interactive features like typing
indicators and real-time message syncing.

Moreover, the Room Chat Application seeks to foster deeper engagement by offering features like random
chat room creation, image sharing, and room-specific customization. Real-time updates, secure room
management, and user-centric functionalities such as profile management and message deletion contribute to
the convenience and reliability of the application. Through the integration of Firebase for real-time
messaging, cloud storage, and authentication, the application ensures secure data management and smooth
performance.

By meticulously developing the application using Xcode, Swift, and Firebase, this project aims to set a new
standard in real-time communication platforms. The goal is to create a space where every interaction is
meaningful, responsive, and aligned with modern user expectations of fast, secure, and customizable
communication. By embracing both technological advancements and user-centric design principles, the
Room Chat Application is poised to redefine how users interact in chat rooms, making it a leader in group
communication solutions.

9
1.1 Aim

The primary aim of this project is to pioneer a state-of-the-art mobile Acrobat Chat Application that
seamlessly transforms the essence of dynamic, real-time communication into a digital experience. By
harnessing the versatile capabilities of Xcode and the streamlined efficiency of Swift, the application
endeavors to set a new benchmark in group chat functionality, offering an unparalleled user experience that
resonates deeply with modern, tech-savvy users.

In today’s competitive digital landscape, where communication platforms are constantly evolving, the
Acrobat Chat Application aims to redefine how users interact with one another in real-time. The project
seeks to create a dynamic and engaging environment where users can create chat rooms, send messages,
share images, and interact in groups seamlessly. This includes not only providing a space for conversations
but also creating an immersive environment where users can enjoy a fluid, intuitive chat experience.

Central to achieving this aim is the application's intuitive design, meticulously crafted to reflect modern
design principles and deliver a user-friendly interface. Through seamless navigation and visually compelling
user interface elements, users will easily create rooms, chat, and engage with friends or random users. This
intuitive approach enhances user satisfaction by ensuring a frictionless communication experience, whether
for casual chats or professional group interactions.

Moreover, the Acrobat Chat Application aims to foster user loyalty by integrating robust functionalities that
enhance convenience and engagement. Features such as secure user authentication, real-time message
syncing, and image-sharing capabilities will streamline the communication process. Real-time notifications
will keep users informed about new messages, group activity, or room invitations, further enriching their
experience.

By leveraging Xcode and Swift, the application will be optimized for speed, responsiveness, and reliability
across various iOS devices. Performance optimization measures will ensure seamless operation, even during
periods of heavy use, reinforcing the application's reliability and usability.

Furthermore, the aim extends beyond simple chat capabilities. The Acrobat Chat Application strives to
establish itself as a hub for group communication, offering a platform where users can not only send
messages but also experience a dynamic, engaging space for real-time interaction. Social features, such as
room customization and media sharing, will foster community engagement and amplify user interaction
organically.

Ultimately, by creating a mobile application that mirrors the interactive experience of real-world group
conversations while leveraging the technological advancements of Xcode and Swift, this project aims to set
a new standard in communication apps. The Acrobat Chat Application seeks to resonate with a global
audience, offering a compelling and cohesive digital experience that embodies the core principles of
innovation, user engagement, and satisfaction.

10
1.2 Objectives

1.2.1 User Interface Development: Designing an intuitive and visually appealing user interface (UI) is
paramount to creating a positive user experience for the Room Chat Application. The UI will reflect the
app's focus on seamless communication, offering cohesive design elements and color schemes that make
navigation straightforward. Visual hierarchy will be employed to highlight key features such as active chat
rooms, user profiles, and notifications, ensuring users can easily access conversations, create new rooms,
and engage with the platform.

1.2.2 Real-time Messaging Integration: Seamless real-time messaging is essential for creating an engaging
user experience in a chat platform. The application will implement robust functionalities such as message
synchronization across devices, image sharing, and group chat creation. The goal is to offer users a fluid and
dynamic communication experience, ensuring messages, notifications, and user interactions are delivered
instantly and securely.

1.2.3 Real-time Notifications: Real-time push notifications will play a crucial role in keeping users
informed and engaged. These notifications will alert users when they receive new messages, are invited to
chat rooms, or when someone starts typing a message. The goal is to personalize notifications based on the
user's activity within the application, keeping them informed of conversations and helping to foster
continuous engagement.

1.2.4 Performance Optimization: Optimizing app performance across various iOS devices is crucial to
delivering a smooth chat experience. Techniques such as real-time data caching, optimizing image
compression, and minimizing loading times will ensure the application operates swiftly and efficiently.
These performance enhancements will be rigorously tested to maintain responsiveness, even during high-
traffic periods, ensuring a reliable user experience.

1.2.5 Cross-device Compatibility: Ensuring compatibility across multiple iOS devices involves
implementing responsive design principles. The Room Chat Application will adapt seamlessly to different
screen sizes and orientations, offering a consistent user experience across iPhones and iPads. This flexibility
maximizes accessibility, allowing users to engage with the application regardless of the device they're using.

1.2.6 Data Security: Implementing strong security measures is essential to protect user data, ensuring
compliance with industry standards such as GDPR. Encryption protocols will be applied to safeguard
personal data, chat history, and images shared within rooms. By prioritizing data security, the app aims to
foster user trust and maintain a secure, privacy-focused environment for all conversations.

1.2.7 Offline Accessibility: Offline capabilities will enhance usability, allowing users to browse saved
messages, access their chat history, and draft messages while offline. Once connectivity is restored, these
messages will automatically sync with the server. This feature will ensure continuous engagement with the
application, even in areas with limited internet availability.

1.2.8 Analytics and Insights: Integrating analytics tools will provide valuable insights into user behavior,
app performance, and usage trends. This data will inform ongoing improvements, such as refining the user
interface, enhancing chat features, and optimizing server performance. Continuous monitoring of user
interactions and message frequency will help tailor the app to meet evolving user preferences and improve
overall satisfaction.

11
1.2.9 Social Integration: Social media integration will enable users to share room links, interesting
conversations, and images with their social networks. By allowing users to seamlessly connect their chat
experiences with platforms like Facebook or Twitter, the app will foster community-driven interactions,
promote user-generated content, and help expand its user base organically through social sharing.

1.2.10 Customer Support Features: In-app customer support, including FAQs, help sections, and live chat,
will be implemented to address user inquiries promptly. By offering accessible and responsive support, the
app ensures a positive user experience, resolves issues in real-time, and establishes itself as a reliable and
customer-centric platform for communication.

12
Chapter 2
SDLC STEPS

13
Fig 2.1 SDLC Steps

A structured Software Development Life Cycle (SDLC) approach was followed for developing this iOS
Room Chat Application. The key phases are:

1. Requirement Analysis
This phase involved gathering and documenting the core features required for the chat application, such as:

User Registration and Login: Implement secure authentication methods for new users and returning
users.

Room-Based Communication: Users must be able to create and join chat rooms and send messages
within those rooms.

Image Messaging: The system should support real-time sending and receiving of images, rather than
text-based messages.

2. System Design
Designing the system architecture involved creating:

Backend Architecture: Firebase was chosen for user authentication, real-time database, and storage
due to its ease of use, security, and scalability.

Frontend Design: Swift (using either UIKit or SwiftUI) was employed to create the login/signup forms,
room creation screens, and chat room interfaces. UI/UX considerations were also a priority to ensure a
smooth user experience.

Database Design: Chat rooms, messages, and user information were structured in Firebase to allow for
efficient data storage and real-time access.

14
3. Implementation
During implementation, both the frontend and backend were developed:

Frontend Development: The app’s interface was built using Swift, ensuring that users could easily
navigate between login, signup, room creation, and chat screens.

Backend Development: Firebase services were integrated for authentication, real-time chat, and image
handling. Firebase Authentication was used for login/signup, while Firebase Realtime Database and Storage
were used for room creation, message storage, and image uploads.

4. Testing
Extensive testing was conducted to ensure the application’s reliability:

Functional Testing: Verified that all core features (e.g., login, room creation, image messaging) worked
as expected.

Integration Testing: Ensured seamless communication between the frontend (Swift) and backend
(Firebase).
UI Testing: Ensured the app’s layout was responsive and user-friendly across various iOS devices.

5. Deployment
The final step involved deploying the app to the Apple App Store:

App Store Preparation: The app was submitted for approval, along with necessary metadata like
descriptions, screenshots, and an app icon.

Firebase Configuration: Final server and storage configurations were completed to ensure the app was
production-ready.

15
6. Maintenance
Post-launch maintenance includes:

Bug Fixes: Addressing any issues encountered by users after the app’s release.

Feature Updates: Enhancing the app with additional functionalities, such as notifications or file sharing.

Performance Optimization: Regularly monitoring and optimizing performance to handle an


increasing user base effectively.

16
Chapter 3

REQUIREMENT SPECIFICATION

3.1 Software Requirement :

1. Operating System iPhone Operating System , MacOS

2. Tools Required XCode 15

3. Frontend Language Swift

4. Designing Language SwiftUI

5. Simulator iOS Simulator

6. Backend Language Swift

7. Database Tool Firebase

Table 3.1 Software Requirement

3.2 Hardware Requirement :

1. Processor Intel processor Apple Silicon M1 chip

2. RAM 16GB

3. ROM 256 GB

Table 3.2 Hardware Requirements

17
Chapter 4
TECHNOLOGY USED

Fig 4.1 Technology Logo

4.1 Frontend-Backend Technology:

4.1.1 Swift:

Fig 4.1.1.1 Swift Logo

Swift is a high-level general-purpose, multi-paradigm, compiled programming language created


by Chris Lattner in 2010 for Apple Inc. and maintained by the open-source community. Swift
compiles to machine code, as it is an LLVM-based compiler. Swift was

18
first released in June 2014,and the Swift toolchain has shipped in Xcode since version 6,
released in 2014.

Apple intended Swift to support many core concepts associated with Objective-C, notably
dynamic dispatch, widespread late binding, extensible programming, and similar features, but in
a "safer" way, making it easier to catch software bugs; Swift has features addressing some
common programming errors like null pointer dereferencing and provides syntactic sugar to
help avoid the pyramid of doom. Swift supports the concept of protocol extensibility, an
extensibility system that can be applied to types, structs and classes, which Apple promotes as a
real change in programming paradigms they term "protocol-oriented programming" (similar to
traits and type classes).

Swift was introduced at Apple's 2014 Worldwide Developers Conference (WWDC). It


underwent an upgrade to version 1.2 during 2014 and a major upgrade to Swift 2 at WWDC
2015. It was initially a proprietary language, but version 2.2 was made open- source
software under the Apache License 2.0 on December 3, 2015, for Apple's platforms and
Linux.

Through version 3.0 the syntax of Swift went through significant evolution, with the core team
making source stability a focus in later versions. In the first quarter of 2018 Swift surpassed
Objective-C in measured popularity.

Swift 4.0, released in 2017, introduced several changes to some built-in classes and structures.
Code written with previous versions of Swift can be updated using the migration functionality
built into Xcode. Swift 5, released in March 2019, introduced a stable binary interface on Apple
platforms, allowing the Swift runtime to be incorporated into Apple operating systems. It is
source compatible with Swift 4.

Swift 5.1 was officially released in September 2019. Swift 5.1 builds on the previous version
of Swift 5 by extending the stable features of the language to compile-time with the
introduction of module stability. The introduction of module stability makes it possible to
create and share binary frameworks that will work with future releases of Swift. Swift 5.5,
officially announced by Apple at the 2021 WWDC, significantly expands language support for
concurrency and asynchronous code, notably introducing aunique version of the actor model.

Swift 5.9, was released in September 2023 and includes a macro system, generic parameter
packs, and ownership features like the new consume operator.The current version, Swift 5.10,
was released in March 2024. This version improves the language's concurrency model,
allowing for full data isolation to prevent data races. It is also the last release before Swift 6.
Version 5.10 is currently available for macOS, Windows and for Linux.

Swift is a general-purpose programming language that’s approachable for newcomers and powerful for
experts. It is fast, modern, safe, and a joy to write.

 Swift is general-purpose and modern. Suitable for everything from systems


programming, through mobile and desktop apps, to cloud services.

19
 Swift is safe. Undefined behavior is the enemy of safety, and it’s best to catch mistakes
before software goes into production. Swift makes the obvious path the safest.
 Swift is fast to run and quick to write. It comes with predictable and consistent
performance that is on-par with C-based languages without sacrificing developer
friendliness.
 Swift is approachable and powerful. From a single-line “Hello, World!” to large-scale apps
with hundreds of thousands of lines. Swift scales with your needs

Features:

Swift includes features that make code easier to read and write, while giving the developer the
control needed in a true systems programming language. Swift supports inferred types to make
code cleaner and less prone to mistakes, and modules eliminate headers and provide
namespaces. Memory is managed automatically, and you don’t even need to type semi-colons.
Swift also borrows from other languages, for instance named parameters brought forward from
Objective-C are expressed in a clean syntax that makes APIs in Swift easy to read and
maintain.

The features of Swift are designed to work together to create a language that is powerful, yet fun
to use. Some additional features of Swift include:

 Closures unified with function pointers


 Tuples and multiple return values
 Generics
 Fast and concise iteration over a range or collection
 Structs that support methods, extensions, and protocols
 Functional programming patterns, e.g., map and filter
 Powerful error handling built-in
 Advanced control flow with do, guard, defer, and repeat keywords

4.2 Database Technology:

4.2.1 Firebase:

Fig 4.2.1 Firebase Logo

20
Firebase is a set of backend cloud computing services and application development platforms
provided by Google. It hosts databases, services, authentication, and integration for a variety of
applications, including Android, iOS, JavaScript, Node.js, Java, Unity, PHP, and C++.

Firebase is a product of Google which helps developers to build, manage, and grow their
apps easily. It helps developers to build their apps faster and in a more secure way. No
programming is required on the firebase side which makes it easy to use its features more
efficiently. It provides services to android, iOS, web, and unity. It provides cloud storage. It
uses No SQL for the database for the storage of data.

Firebase initially was an online chat service provider to various websites through API and
ran with the name Envolve. It got popular as developers used it to exchange application data
like a game state in real time across their users more than the chats. This resulted in the
separation of the Envolve architecture and its chat system. The Envolve architecture was
further evolved by its founders James Tamplin and Andrew Lee, to what modern day
Firebase is in the year 2012.

Firebase has been claimed to be used by Google to track users without their knowledge. On
July 14, 2020, a lawsuit was filed accusing Google of violating federal wire tap law and
California privacy law. It stated that through Firebase, Google collected and stored user data,
logging what the user was looking at in many types of apps, despite the user following
Google's own instructions to turn off the web and app activity collected by the company.The
lawsuit was dismissed in January 2022, with Chief US District Judge Richard Seeborg ruling
that a promise to avoid collecting user data did not amount to a contract.

Key Features:

1. Authentication: It supports authentication using passwords, phone numbers, Google,


Facebook, Twitter, and more. The Firebase Authentication (SDK) can be used to manually
integrate one or more sign-in methods into an app.

2. Realtime database: Data is synced across all clients in realtime and remains available even
when an app goes offline.

3. Hosting: Firebase Hosting provides fast hosting for a web app; content is cached into
content delivery networks worldwide.

4. Test lab: The application is tested on virtual and physical devices located in Google’s data
centers.

5. Notifications: Notifications can be sent with firebase with no additional coding.Users can
get started with firebase for free; more details can be found on the official website.

21
4.3 Tools Required:

4.3.1 XCode 15:

Fig 4.3.1 Xcode Logo

Xcode 15 enables you to develop, test, and distribute apps for all Apple platforms. Code
and design your apps faster with enhanced code completion, interactive previews, and live
animations. Use Git staging to craft your next commit without leaving your code. Explore
and diagnose your test results with redesigned test reports with video recording. And start
deploying seamlessly to TestFlight and the App Store from Xcode Cloud. Creating amazing
apps has never been easier. Xcode 15 includes SDKs for iOS 17, iPadOS 17, tvOS 17, watchOS
10, and macOS Sonoma. The Xcode 15 release supports on-device debugging in iOS 12 and later,
tvOS 12 and later, and watchOS 4 and later. Xcode 15 requires a Mac running macOS Ventura
13.5 or later.

Xcode 15 is now 50% smaller on the Mac App Store, with downloadable simulator runtimes for all
platforms. Enhanced code completion helps you write safer code faster, now referencing all your
assets. And projects build faster thanks to improvements in the compiler and a brand- new linker,
optimized for the multicore architecture of Apple silicon.

The new Bookmark navigator helps you keep track of landmarks in your code and organize your
tasks. Localization assets are streamlined in the new String Catalog, giving you a centralized way
to review and update them. And documentation shines in Xcode 15, with a beautiful new design,
and real-time preview.

Swift, SwiftUI, and Xcode 15 work together as one. Powered by the new Swift macros, Xcode
Previews are easier to use and now work across SwiftUI, UIKit, and AppKit. The new interactive
timeline helps you develop and design your widgets. And working with different platforms and
devices is easier: you can choose them right in the preview canvas to make sure your views look
great everywhere.

Use the power of macros in the source editor, setting breakpoints and stepping into the generated
code. Access debug output with ease using the structured console.

Xcode 15 and Xcode Cloud work seamlessly together. Xcode Cloud is a continuous integration and
delivery service built into Xcode and designed expressly for Apple developers. Start building your
app in just a few minutes, with live build status, beautiful reports, and automatic distribution to
your testers and users.

22
Chapter 5
PROJECT DESIGN

5.1 E-R Diagram

Fig 5.1 E-R Diagram

23
5.2 DFD Diagram

5.2.1 Level-0 DFD

Fig 5.2.1 Level-0 DFD

5.2.2 Level-1 DFD

Fig 5.2.2 Level-1 DFD

24
5.2.3 Level-2 DFD

Fig 5.2.3 Level-2 DFD

25
Chapter 6
SNAPSHOTS
6.1 Frontend Snapshots:

6.1.1 Register Page:

Fig 6.1.1 This is the Registeration Page of the iOS application of Acrobat Chat Application where
user register himself to the application and he can further go with the functioning of the Chat
Application.

26
6.1.2 Login Page:

Fig 6.1.2 This is the Login page of the application through verifying the entered email
and password authenticate user could enter into the application by logging into it.

27
6.1.3 Home Page:

Fig 6.1.3 Home Page of the application shows all the functioning of the application
from this page we can go to all other pages and create room are also shown on this page
according to the various types of room are created . This could be done by applying
Collection View functioning through swift and by using separate XIB file for the cells.

28
6.1.4 Room Creation Page:

Fig 6.1.4 This is the Page where Create the room chat of the application is shown in the
one page only. Scroll view element of SwiftUI is used to make it visible on the single
Page.

29
6.1.5 Room Deletion Page:

Fig 6.1.5 Room Deletion Page which show the room created name which we give the
long press on the created room then deletion button will be appear .

30
6.1.6 Chat Page:

6.1.6 Chat Screen is the main interface where users engage in one-on-one or group
conversations within the application. It provides a streamlined experience for sending and
receiving messages, while managing various background functionalities like real-time
updates and UI rendering.

31
6.1.7 Send Image Page: In That chat Conversation we send the Image to each other

32
Fig 6.1.8 In that page which shows that conversation between users they typing the
message and when they type message then show the typing indicator.

33
6.1.9 Conversation Page:

Fig 6.1.9 In the chat room we message the random person through the own user
name to each other.

34
6.1.10 Conversation Deletion Page:

Fig 6.1.10 When the user want to delete the message in group conversation then which
message want to delete select it and press the message then Delete message option will
be appear if they want to delete.

6.1.11 Application Navigation Setup

35
6.2 Backend Snapshots:

Database Snapshots:

Fig 6.2.1 Table-1

Fig 6.2.2 Table-2

36
Fig 6.2.3 Table-3

Fig 6.2.4 Table-4

37
Chapter 7

TESTING

Software testing is any activity aimed at evaluating an attribute or capability of a program


or system and determining that it meets its required results. Although crucial to software
quality and widely deployed by programmers and testers, software testing still remains an
art, due to limited understanding of the principles of software.

UNIT TESTING

MODULE TESTING

SUB-SYSTEM TESTING
Component Testing

SYSTEM TESTING

Integration Testing

ACCEPTANCE
TESTING

User Testing

Fig 7.1 Testing

38
For the iOS shoe store e-commerce application, you can structure the testing into different
phases to ensure a thorough and seamless user experience. Here's a detailed breakdown of each
phase:

7.1 Unit Testing Phase:

Objective: Verify the correctness of individual components and ensure that specific features function as
expected in isolation.
Focus:

 UI Components: Test UI elements like navigation controllers, chat input boxes, and user interface
buttons (e.g., send, attach image, create room) to confirm responsiveness and visual correctness.
 Core Logic: Ensure that critical functions such as room creation, message sending/receiving, and
image attachment are working correctly.
 Data Handling: Validate that chat room data is fetched correctly from the database, with proper
error handling for failed API requests (e.g., Firebase connections).

7.2 Integration Testing Phase:

Objective: Test the interaction between different components to ensure they work together smoothly.
Focus:

 Authentication & Room Sync: Check if users' room selections and chat messages sync properly
across different devices after login/logout.
 Room Chat & Messaging: Ensure that the chat messages interact properly with the chat room data
and that messages are displayed in real-time when users join, send, or receive messages.
 Image Sending: Confirm that the image sending system integrates well with the chat flow, ensuring
that images are properly uploaded and displayed.

7.3 User Interface Testing Phase:

Objective: Ensure the app provides a smooth and intuitive experience for users.
Focus:

 Navigation: Test the app's flow, ensuring smooth transitions between rooms, and confirm that users
can easily create rooms, navigate through group chats, and send messages or images without
confusion.
 Layout Consistency: Validate that the app renders correctly across different iOS devices, ensuring
responsive design for various screen sizes.
 Interactive Elements: Confirm that all clickable elements, such as room creation buttons, send
message buttons, and image attachment icons, function as intended without lag or errors.

7.4 Performance Testing Phase:

Objective: Ensure that the app performs efficiently under different conditions, providing a smooth
experience even when heavily used.
Focus:

 Loading Times: Measure the time taken to load chat messages, images, and room lists from the
database.
 Response Times: Ensure that real-time functionalities, such as message sending and receiving,
respond quickly and without delay.

39
 Scalability: Simulate high-traffic scenarios to test the app's ability to handle multiple users chatting
simultaneously in various rooms.

7.5 Security Testing Phase:

Objective: Verify that the app is secure and protects user data from potential threats.
Focus:

 User Authentication: Test for vulnerabilities in login systems, ensuring secure sign-in processes
with email, Google, and Apple ID.
 Data Protection: Ensure that sensitive data, such as private messages and room data, is securely
stored and transmitted using encryption.
 Backend Security: Validate that communication with Firebase is secure, protecting against
unauthorized access and ensuring data integrity.

7.6 Usability Testing Phase:

Objective: Assess the overall user experience, ensuring the app is easy to navigate and intuitive to use.
Focus:

 User Navigation: Test how real users interact with the app, ensuring that tasks like joining chat
rooms, sending messages, and attaching images are intuitive and easy to perform.
 Visual Clarity: Ensure that chat messages, user names, and buttons are clear and accessible.
 User Feedback: Gather insights from potential users to identify areas where improvements in user
experience can be made.

7.7 Beta Testing Phase:

Objective: Conduct real-world testing by releasing a beta version to a selected group of users.
Focus:

 Real-world Usage: Gather feedback from a controlled group of users to identify any issues or bugs
that may not have been caught in earlier testing phases.
 User Experience: Monitor user behavior, collecting data on pain points, app crashes, and overall
satisfaction with the app’s performance.
 Performance in Different Environments: Test how the app performs under various conditions,
such as different network speeds and device types.

7.8 Regression Testing Phase:

Objective: Ensure that newly implemented features or bug fixes do not break existing functionalities.
Focus:

 Re-testing Key Features: After every update or change in the codebase, re-test critical app features
such as chat room creation, message sending, and image attachment.
 Previous Bug Fixes: Confirm that previously resolved bugs have not resurfaced and that the app
remains stable throughout.

40
Chapter 8

FUTURE SCOPE OF THE PROJECT

Here’s the future scope for the iOS e-commerce shoe store application, presented with brief
descriptions:

8.1 Expansion of Product Catalog: Integrate personalized product recommendations based


on user behavior, purchase history, and preferences to enhance customer engagement and offer
tailored suggestions.

8.2 Augmented Reality (AR) Integration: Use AR technology to allow users to


virtually try on shoes via their phone’s camera, improving the buying decision process and
reducing product returns.

8.3 Enhanced Payment Options: Offer more payment methods, such as cryptocurrency or
installment options (e.g., "Buy Now, Pay Later"), to cater to a wider range of customers and
improve purchase flexibility.

8.4 Voice Search and Assistance: Add voice search and command features, enabling users
to search for products, manage their cart, and complete purchases using voice commands,
enhancing accessibility and convenience.

8.5 Loyalty Program and Rewards System: Implement a rewards system where users
earn points for purchases, reviews, and referrals, which can be redeemed for discounts or
exclusive products, fostering customer loyalty.

8.6 Social Shopping Features: Enable users to share products and wish lists on social
media or shop collaboratively, creating a social and community-driven shopping experience that
boosts brand visibility.

8.7 AI-Powered Customer Support: Introduce AI-driven chatbots for real-time customer
support, assisting users with product inquiries, order tracking, and troubleshooting, ensuring faster
and more efficient service.

8.8 Multi-Language and Multi-Currency Support: Expand the app with support for
multiple languages and currencies to cater to an international audience, making the platform
accessible to global customers.

8.9 Push Notification Personalization: Use personalized push notifications to alert users
about abandoned carts, exclusive promotions, or product recommendations based on their
behavior, increasing engagement.

41
8.10 Offline Mode for Browsing: Allow users to browse a cached version of the product
catalog and previously viewed items offline, ensuring a smoother experience in areas with poor
connectivity.

8.11 Subscription-based Services: Offer a subscription model where users can get
exclusive access to limited-edition shoes, early sales, or special discounts, generating recurring
revenue and building customer loyalty.

8.12 Data Analytics and Insights for Sellers: Provide real-time analytics to store
owners, helping them track sales, customer trends, and inventory, empowering them to make data-
driven decisions.

8.13 Green Initiatives: Introduce eco-friendly options like carbon-neutral shipping or


tracking the environmental impact of purchases, appealing to environmentally conscious users.

8.14 Advanced Search with Image Recognition: Allow users to upload images of shoes
and receive recommendations for visually similar products through image recognition technology,
improving search convenience.

8.15 Community and User-generated Content: Build a community section where users
can share photos, write reviews, and discuss products, fostering a sense of community and
building trust through real customer experiences.

These brief points outline the potential enhancements and innovations that could improve user
engagement, broaden the app’s appeal, and create a more interactive shopping experience.

42
Chapter 9

CONCLUSION
The development of an iOS-based room chat application utilizing Swift and Firebase represents a significant
advancement in creating a feature-rich and user-friendly platform for real-time communication. With a clean
and intuitive interface powered by SwiftUI, seamless real-time messaging through Firebase Firestore, and
robust user authentication, the app successfully provides users with a smooth and engaging chat experience.
Key functionalities like room creation, group chatting, image sharing, and typing indicators offer users a
comprehensive and enjoyable interaction.

The application is designed to meet current user demands while allowing for future enhancements. Features
like augmented reality (AR) integration for virtual meetups, advanced chat moderation tools, and multi-
language support provide opportunities for growth and innovation, ensuring the app remains relevant in the
rapidly evolving communication landscape.

By incorporating user feedback during various testing phases and optimizing performance, the app
demonstrates a commitment to delivering quality and convenience. Additional enhancements, such as
personalized notifications, user status updates, and expanded media sharing options, can further engage and
retain users.

In conclusion, this project lays the foundation for a highly scalable and interactive platform that meets both
the functional and aesthetic needs of users. The app’s strong backend, modern UI design, and future
potential make it a promising solution for the growing demands of online communication, particularly in
group chat scenarios. With further development and features, this platform has the capacity to evolve into a
fully-fledged, industry-leading chat solution.

43
Chapter 10

BIBLIOGRAPHY AND REFERENCES


1. www.javatpoint.com
2. www.tutorialspoint.com
3. www.w3schools.com
4. www.medium.com

44
PROJECT STRUCTURE &CODING:

1. Structure:

45
2. Pod file

3. Coding

1. SignFormCell

46
2. Validation Form

3. Room Creation

47
4. Conversation ID

5. Upload Image

6. Send Image

48
7. Delete Message

8. Chat cell
import UIKit

class ChatCell: UITableViewCell {


enum BubbleType {
case incoming
case outgoing
}

@IBOutlet weak var chatStack: UIStackView!


@IBOutlet weak var textView: UITextView!
@IBOutlet weak var textViewBubbleView: UIView!
@IBOutlet weak var senderNameLabel: UILabel!

var messageImageView: UIImageView!

override func awakeFromNib() {


super.awakeFromNib()

self.textViewBubbleView.layer.cornerRadius = 7
self.textView.textContainerInset = UIEdgeInsets(top: 10, left: 5, bottom: 10, right: 5)
49
// Initialize and configure the messageImageView
messageImageView = UIImageView()
messageImageView.translatesAutoresizingMaskIntoConstraints = false
messageImageView.contentMode = .scaleAspectFill
messageImageView.clipsToBounds = true
messageImageView.layer.cornerRadius = 7
messageImageView.isHidden = true

// Add the messageImageView to the chatStack


chatStack.addArrangedSubview(messageImageView)

// Add constraints to the messageImageView


NSLayoutConstraint.activate([
messageImageView.heightAnchor.constraint(equalToConstant: 200),
messageImageView.widthAnchor.constraint(equalTo: chatStack.widthAnchor)
])
}

func setBubbleDataForMessage(message: Message) {


if let messageText = message.messageText {
self.textView.isHidden = false
self.textViewBubbleView.isHidden = false
self.textView.text = messageText
self.messageImageView.isHidden = true
} else if let imageLink = message.imageLink {
self.textView.isHidden = true
self.textViewBubbleView.isHidden = true
self.textView.text = "" // Clear text
self.messageImageView.isHidden = false
loadImage(from: imageLink)
}

self.senderNameLabel.text = message.senderUsername
}

func setBubbleType(type: BubbleType) {


switch type {
case .outgoing:
self.chatStack.alignment = .trailing
self.textViewBubbleView.backgroundColor = #colorLiteral(red: 0.059805127, green:
0.2340934603, blue: 0.245598033, alpha: 1)
self.textView.textColor = .white
case .incoming:
self.chatStack.alignment = .leading
self.textViewBubbleView.backgroundColor = #colorLiteral(red: 0.8039215803, green:
0.8039215803, blue: 0.8039215803, alpha: 1)
self.textView.textColor = .black
}
}

private func loadImage(from url: String) {


guard let imageURL = URL(string: url) else { return }
50
URLSession.shared.dataTask(with: imageURL) { data, response, error in
guard let data = data, error == nil else { return }
DispatchQueue.main.async {
self.messageImageView.image = UIImage(data: data)
}
}.resume()
}

override func setSelected(_ selected: Bool, animated: Bool) {


super.setSelected(selected, animated: animated)
}
}

9. Chat Room View Controller


//
// ChatRoomsViewController.swift
// Acrobat
//
// Created by Apple 9 on 20/06/24.
//

import UIKit
import Firebase
import FirebaseAuth
import FirebaseDatabase

class ChatRoomsViewController: UIViewController, UITableViewDelegate,


UITableViewDataSource {

@IBOutlet weak var newRoomTextField: UITextField!


@IBOutlet weak var chatRoomsTable: UITableView!

var rooms = [Room]()


var messages = [Message]() // Array to store last messages

override func viewDidLoad() {


super.viewDidLoad()

self.chatRoomsTable.delegate = self
self.chatRoomsTable.dataSource = self

observeRooms()
fetchLastMessages()
}

func observeRooms() {
let roomsRef = Database.database().reference().child("rooms")
51
roomsRef.observe(.childAdded) { (snapshot) in
if let roomData = snapshot.value as? [String: Any] {
var modelData = Room(array: roomData)
modelData.roomId = snapshot.key

self.rooms.append(modelData)
self.chatRoomsTable.reloadData()
}
}
}

func fetchLastMessages() {
for room in rooms {
guard let roomId = room.roomId else {
continue
}

// Observe the last child added in the room


Database.database().reference().child("messages").child(roomId).queryLimited(toLast:
1).observe(.childAdded, with: { (snapshot) in
let messageId = snapshot.key

// Retrieve the message details from the specific child node

Database.database().reference().child("messages").child(roomId).child(messageId).observeSingl
eEvent(of: .value, with: { (snapshot) in
if let dict = snapshot.value as? [String: Any] {
if let messageText = dict["messageText"] as? String,
let senderId = dict["senderId"] as? String,
let senderUsername = dict["senderUsername"] as? String,
let imageLink = dict["imageLink"] as? String {

// Create a Message object and store it in messages array


let message = Message(messageId: messageId,
senderId: senderId,
messageText: messageText,
senderUsername: senderUsername,
imageLink: imageLink)

self.messages.append(message)

self.chatRoomsTable.reloadData()
}
}
}) { (error) in
print("Failed to fetch message with error:", error.localizedDescription)
}
}) { (error) in
print("Failed to observe last message with error:", error.localizedDescription)
}
}
}
52
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)

if Auth.auth().currentUser == nil {
let loginViewController = self.storyboard?.instantiateViewController(withIdentifier:
"LoginView") as! ViewController
self.present(loginViewController, animated: true, completion: nil)
}
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {


return self.rooms.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->


UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "RoomCell", for: indexPath)
let room = self.rooms[indexPath.row]
cell.textLabel?.text = room.name

// Example: Display last message if available


if indexPath.row < self.messages.count {
let message = self.messages[indexPath.row]
cell.detailTextLabel?.text = message.messageId
}

return cell
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {


let room = self.rooms[indexPath.row]
let chatViewController = self.storyboard?.instantiateViewController(withIdentifier:
"RoomViewController") as! RoomViewController
chatViewController.room = room
self.navigationController?.pushViewController(chatViewController, animated: true)
}

@IBAction func didPressCreateChatRoom(_ sender: UIButton) {


guard let userId = Auth.auth().currentUser?.uid,
let roomName = self.newRoomTextField.text,
!roomName.isEmpty else {
return
}

self.newRoomTextField.resignFirstResponder()

let databaseRef = Database.database().reference()


let roomRef = databaseRef.child("rooms").childByAutoId()
let roomData: [String: Any] = ["creatorId": userId, "name": roomName]

roomRef.setValue(roomData) { (error, ref) in


53
if let error = error {
print("Error creating chat room:", error.localizedDescription)
return
}

self.newRoomTextField.text = ""
}
}

@IBAction func didPressLogout(_ sender: UIBarButtonItem) {


do {
try Auth.auth().signOut()
let loginViewController = self.storyboard?.instantiateViewController(withIdentifier:
"LoginView") as! ViewController
self.present(loginViewController, animated: true, completion: nil)
} catch {
print("Error signing out:", error.localizedDescription)
}
}
}

10. Room View Controller


import UIKit
import Firebase
import FirebaseAuth
import FirebaseDatabase
import FirebaseStorage

class RoomViewController: UIViewController, UITableViewDelegate,


UITableViewDataSource, UIImagePickerControllerDelegate, UINavigationControllerDelegate {

@IBOutlet weak var messagesTable: UITableView!


@IBOutlet weak var newMessageTextField: UITextField!

var room: Room?


var messages = [Message]()
var typingUsers: [String: String] = [:] // Store userId and username
var typingIndicatorLabel: UILabel!

override func viewDidLoad() {


super.viewDidLoad()

self.navigationItem.title = self.room?.name

self.messagesTable.delegate = self
self.messagesTable.dataSource = self
self.messagesTable.separatorStyle = .none
self.messagesTable.allowsSelection = false

setupTypingIndicator()
observeMessages()
54
observeTypingIndicator()

newMessageTextField.addTarget(self, action: #selector(textFieldDidChange(_:)), for:


.editingChanged)
}

func setupTypingIndicator() {
typingIndicatorLabel = UILabel()
typingIndicatorLabel.translatesAutoresizingMaskIntoConstraints = false
typingIndicatorLabel.textColor = .gray
view.addSubview(typingIndicatorLabel)

NSLayoutConstraint.activate([
typingIndicatorLabel.bottomAnchor.constraint(equalTo: messagesTable.bottomAnchor,
constant: -10),
typingIndicatorLabel.leadingAnchor.constraint(equalTo: messagesTable.leadingAnchor,
constant: 15)
])
}

func observeMessages() {
guard let roomId = self.room?.roomId else {
print("Error: Room ID is nil")
return
}

let messagesRef =
Database.database().reference().child("rooms").child(roomId).child("messages")

messagesRef.observe(.childAdded) { (snapshot) in
if let data = snapshot.value as? [String: Any],
let senderId = data["senderId"] as? String,
let senderName = data["senderName"] as? String,
let messageId = snapshot.key as? String {

var message: Message?

if let text = data["text"] as? String {


message = Message(messageId: messageId, senderId: senderId, messageText: text,
senderUsername: senderName, imageLink: nil)
} else if let imageLink = data["imageLink"] as? String {
message = Message(messageId: messageId, senderId: senderId, messageText: nil,
senderUsername: senderName, imageLink: imageLink)
}

if let message = message {


self.messages.append(message)
self.messagesTable.reloadData()
self.scrollToLastMessage()
}
}
}
}
55
func observeTypingIndicator() {
guard let roomId = self.room?.roomId else { return }
let typingRef =
Database.database().reference().child("rooms").child(roomId).child("typing")

typingRef.observe(.childAdded) { snapshot in
let userId = snapshot.key
self.fetchUsername(for: userId) { username in
if let username = username {
self.typingUsers[userId] = username
self.updateTypingIndicator()
}
}
}

typingRef.observe(.childRemoved) { snapshot in
let userId = snapshot.key
self.typingUsers.removeValue(forKey: userId)
self.updateTypingIndicator()
}
}

func fetchUsername(for userId: String, completion: @escaping (String?) -> Void) {


let userRef = Database.database().reference().child("users").child(userId).child("username")
userRef.observeSingleEvent(of: .value) { snapshot in
completion(snapshot.value as? String)
}
}

func updateTypingIndicator() {
if typingUsers.isEmpty {
typingIndicatorLabel.text = ""
} else {
typingIndicatorLabel.text = typingUsers.values.joined(separator: ", ") + " is typing..."
}
}

@objc func textFieldDidChange(_ textField: UITextField) {


sendTypingIndicator(typing: !textField.text!.isEmpty)
}

func sendTypingIndicator(typing: Bool) {


guard let userId = Auth.auth().currentUser?.uid, let roomId = self.room?.roomId else {
return }
let typingRef =
Database.database().reference().child("rooms").child(roomId).child("typing").child(userId)

if typing {
typingRef.setValue(true)
} else {
typingRef.removeValue()
}
56
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) ->


UITableViewCell {
let message = self.messages[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "ChatCell2", for: indexPath) as!
ChatCell

if let currentUserUid = Auth.auth().currentUser?.uid, currentUserUid == message.senderId


{
cell.setBubbleType(type: .outgoing)
} else {
cell.setBubbleType(type: .incoming)
}

cell.setBubbleDataForMessage(message: message)

// Add long press gesture to delete message


let longPressGesture = UILongPressGestureRecognizer(target: self, action:
#selector(handleLongPress(_:)))
cell.addGestureRecognizer(longPressGesture)

return cell
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {


return self.messages.count
}

@IBAction func didPressSendMessage(_ sender: UIButton) {


if let messageText = self.newMessageTextField.text {
self.sendMessage(text: messageText, imageLink: nil)
}
}

func sendMessage(text: String?, imageLink: String?) {


guard let userId = Auth.auth().currentUser?.uid, let roomId = self.room?.roomId else {
print("Error: User ID or Room ID is nil")
return
}

let roomRef = Database.database().reference().child("rooms").child(roomId)


let newMessageRef = roomRef.child("messages").childByAutoId()

let ref = Database.database().reference().child("users").child(userId).child("username")

ref.observeSingleEvent(of: .value) { (snapshot) in


if let userName = snapshot.value as? String {
var messageData: [String: Any] = ["senderId": userId, "senderName": userName,
"date": ServerValue.timestamp()]

if let text = text {


messageData["text"] = text
57
} else if let imageLink = imageLink {
messageData["imageLink"] = imageLink
}

newMessageRef.updateChildValues(messageData)
}
}

self.newMessageTextField.text = ""
self.newMessageTextField.resignFirstResponder()
sendTypingIndicator(typing: false)
}

@IBAction func didPressImagePickerButton(_ sender: UIButton) {


let imagePicker = UIImagePickerController()
imagePicker.allowsEditing = true
imagePicker.delegate = self

self.present(imagePicker, animated: true, completion: nil)


}

func imagePickerController(_ picker: UIImagePickerController,


didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
var selectedImage: UIImage?

if let editedImage = info[.editedImage] as? UIImage {


selectedImage = editedImage
} else if let originalImage = info[.originalImage] as? UIImage {
selectedImage = originalImage
}

if let selectedImage = selectedImage {


self.uploadImageToFirebase(image: selectedImage)
}

self.dismiss(animated: true, completion: nil)


}

func uploadImageToFirebase(image: UIImage) {


guard let imageData = image.jpegData(compressionQuality: 0.5) else {
print("Could not convert image to data.")
return
}

let storageRef = Storage.storage().reference().child("images/\(UUID().uuidString).jpg")

storageRef.putData(imageData, metadata: nil) { (metaData, error) in


if let error = error {
print("Error uploading image: \(error.localizedDescription)")
return
}

storageRef.downloadURL { (url, error) in


58
if let error = error {
print("Error getting download URL: \(error.localizedDescription)")
return
}

if let downloadURL = url {


self.sendMessage(text: nil, imageLink: downloadURL.absoluteString)
}
}
}
}

@IBAction func didPressBackButton(_ sender: UIButton) {


self.navigationController?.popViewController(animated: true)
}

override func didReceiveMemoryWarning() {


super.didReceiveMemoryWarning()
}

// MARK: - Delete Message

func deleteMessage(_ message: Message, at indexPath: IndexPath) {


guard let roomId = room?.roomId else { return }

let messageRef =
Database.database().reference().child("rooms").child(roomId).child("messages")
let messageKey = message.messageId

messageRef.child(messageKey).removeValue { error, _ in
if let error = error {
print("Error deleting message: \(error.localizedDescription)")
} else {
self.messages.remove(at: indexPath.row)
self.messagesTable.reloadData()
}
}
}

@objc func handleLongPress(_ gesture: UILongPressGestureRecognizer) {


guard gesture.state == .began else { return }
let point = gesture.location(in: messagesTable)
guard let indexPath = messagesTable.indexPathForRow(at: point) else { return }

let message = messages[indexPath.row]


let alert = UIAlertController(title: "Delete Message", message: "Are you sure you want to
delete this message?", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
alert.addAction(UIAlertAction(title: "Delete", style: .destructive, handler: { _ in
self.deleteMessage(message, at: indexPath)
}))

present(alert, animated: true, completion: nil)


59
}

private func scrollToLastMessage() {


let lastSection = self.messagesTable.numberOfSections - 1
let lastRow = self.messagesTable.numberOfRows(inSection: lastSection) - 1
if lastRow >= 0 {
let indexPath = IndexPath(row: lastRow, section: lastSection)
self.messagesTable.scrollToRow(at: indexPath, at: .bottom, animated: true)
}
}
}

60

You might also like