Quickstarters
CRUD Samples
How to Develop a Basic CRUD Application with SwiftUI?
28 min
overview in this guide, you will learn how to develop a fully functional crud (create, read, update, and delete) application using swiftui swiftui is a framework for building user interfaces for ios, ipados, watchos, tvos, visionos, and macos we'll use back4app as the backend service to manage our data this tutorial walks you through configuring your back4app project, designing your database schema, integrating with swiftui using api calls, and securing your backend what you'll learn how to construct a crud app that handles data operations seamlessly techniques for designing a robust and scalable backend methods to connect a swiftui interface with back4app using rest apis how to manage data securely with advanced access controls prerequisites back4app account ensure you have signed up and set up a new project on back4app refer to back4app quickstart https //www back4app com/docs/get started/new parse app for assistance swiftui environment confirm that you have xcode installed and a basic swiftui project created familiarity basic knowledge of swift, swiftui, and restful apis will be helpful before you start step 1 – establishing your back4app project initiate a new project on back4app access your back4app dashboard by logging into your account select “new app” to begin a fresh project name your project for example, basic crud app swiftui , and follow the on screen directions to complete the setup create new project once your project is created, it will appear in your dashboard, ready to be configured for backend operations step 2 – crafting your database schema defining your data model for this crud application, you need to define several collections (classes) below are examples that outline key collections along with their fields and types 1\ collection items this collection stores details about each entry field type purpose id objectid auto generated primary key title string name or title of the item description string brief explanation about the item created at date timestamp marking creation updated at date timestamp of the latest update 2\ collection users this collection contains user credentials and profile details field type purpose id objectid auto generated unique identifier username string unique username for login email string user's unique email address password hash string encrypted password for authentication created at date account creation timestamp updated at date timestamp of last account modification you can configure these classes manually via the back4app dashboard by creating new classes and adding columns for each field create new class utilize the dashboard tools to define the field name, type, default value, and required status create column leveraging the back4app ai agent the back4app ai agent streamlines the process of schema generation it can automatically produce your database schema based on a textual prompt how to utilize the ai agent locate the ai agent sign in and navigate to the ai agent section in your project settings submit your schema description input a detailed prompt that outlines the desired collections and fields review and implement after generation, verify the schema and apply the changes sample prompt create these collections in my back4app project 1\) collection items \ fields \ id objectid (auto generated) \ title string \ description string \ created at date (auto generated) \ updated at date (auto updated) 2\) collection users \ fields \ id objectid (auto generated) \ username string (unique) \ email string (unique) \ password hash string \ created at date (auto generated) \ updated at date (auto updated) this feature saves time and ensures consistency in your database setup step 3 – managing data with the admin interface overview of the admin interface the back4app admin app is a no code tool that simplifies data management its intuitive drag and drop interface enables you to perform crud operations effortlessly activating the admin interface go to the “more” menu in your back4app dashboard select “admin app” and then choose “enable admin app ” set up credentials create your initial admin user, which configures system roles automatically enable admin app after activation, log into the admin app to manage your collections admin app dashboard crud operations in the admin interface create use the “add record” option in any collection (e g , items) to add new data read/update click on a record to view details and modify fields delete remove records using the delete function when they are no longer needed this interface enhances usability and simplifies everyday data operations step 4 – integrating swiftui with back4app with your backend in place, it’s time to connect your swiftui application to back4app using rest api calls in swiftui instead of relying on the sdk, we’ll use rest api calls to interact with back4app from our swiftui app example fetching items create a new swiftui view (e g , itemslistview\ swift ) and add the following code import swiftui import combine struct item identifiable, codable { let id string let title string let description string } class itemsviewmodel observableobject { @published var items \[item] = \[] private var cancellables = set\<anycancellable>() func fetchitems() { guard let url = url(string "https //parseapi back4app com/classes/items") else { return } var request = urlrequest(url url) request addvalue("your application id", forhttpheaderfield "x parse application id") request addvalue("your rest api key", forhttpheaderfield "x parse rest api key") urlsession shared datataskpublisher(for request) map { $0 data } decode(type itemsresponse self, decoder jsondecoder()) receive(on dispatchqueue main) sink(receivecompletion { completion in if case let failure(error) = completion { print("error fetching items \\(error)") } }, receivevalue { response in self items = response results }) store(in \&cancellables) } } struct itemsresponse codable { let results \[item] } struct itemslistview view { @stateobject private var viewmodel = itemsviewmodel() var body some view { navigationview { list(viewmodel items) { item in vstack(alignment leading) { text(item title) font( headline) text(item description) font( subheadline) } } navigationtitle("items") onappear { viewmodel fetchitems() } } } } struct itemslistview previews previewprovider { static var previews some view { itemslistview() } } this view fetches data from back4app via rest and displays it in a list further api operations creating new items use urlsession with a post request to add new entries updating items implement put requests for modifying existing data deleting items utilize delete requests to remove data integrate these network operations within your swiftui views as needed step 5 – securing your backend implementing access controls protect your data by setting access control lists (acls) for your objects for example, to create a secure item record func createsecureitem(title string, description string, ownerid string) { guard let url = url(string "https //parseapi back4app com/classes/items") else { return } var request = urlrequest(url url) request httpmethod = "post" request addvalue("your application id", forhttpheaderfield "x parse application id") request addvalue("your rest api key", forhttpheaderfield "x parse rest api key") request addvalue("application/json", forhttpheaderfield "content type") let itemdata \[string any] = \[ "title" title, "description" description, "acl" \[ ownerid \["read" true, "write" true], " " \["read" false, "write" false] ] ] request httpbody = try? jsonserialization data(withjsonobject itemdata) urlsession shared datatask(with request) { data, response, error in if let error = error { print("error creating item \\(error)") } } resume() } configuring class level permissions within your back4app dashboard, adjust class level permissions (clps) for each collection to enforce who can read or write data by default step 6 – implementing user authentication establishing user accounts back4app leverages a user class to handle authentication in your swiftui app, manage registration and login via rest api calls example user registration func signupuser(username string, password string, email string) { guard let url = url(string "https //parseapi back4app com/users") else { return } var request = urlrequest(url url) request httpmethod = "post" request addvalue("your application id", forhttpheaderfield "x parse application id") request addvalue("your rest api key", forhttpheaderfield "x parse rest api key") request addvalue("application/json", forhttpheaderfield "content type") let userdata \[string any] = \[ "username" username, "password" password, "email" email ] request httpbody = try? jsonserialization data(withjsonobject userdata) urlsession shared datatask(with request) { data, response, error in if let error = error { print("sign up error \\(error)") } else { print("user registered successfully") } } resume() } this approach can be extended for user login and session management step 7 – conclusion and future enhancements great job! you’ve successfully built a basic crud application using swiftui and back4app you created a project titled basic crud app swiftui , designed your database schema for items and users, and connected your swiftui frontend to the backend via rest api calls additionally, you learned how to secure your data with acls and implement user authentication what’s next? expand your ui enhance your swiftui interface with detailed views, animations, and interactive elements advanced features incorporate additional backend logic such as cloud functions or real time data updates explore more visit the back4app documentation https //www back4app com/docs for further insights into optimizing your app and integrating more advanced functionalities by following this guide, you now have the essential skills to create a robust and scalable crud backend for your swiftui applications using back4app enjoy building and innovating!