Quickstarters
Feature Overview
How to build a backend for SwiftUI?
41 min
introduction in this tutorial, you’ll learn how to build a complete backend for a swiftui ios app using back4app we'll show you how to integrate the parse swift sdk into your swiftui project and take advantage of key back4app features—like database management, cloud code functions, rest and graphql apis, user authentication, and real time queries—to create a secure, scalable backend this approach helps you store data securely, run server side operations without setting up your own infrastructure, and easily scale your ios app or web app as needed you’ll also see how back4app’s quick setup and intuitive environment can drastically reduce the time and effort compared to manually configuring your own server and database by the end, you’ll understand how to build a backend for swiftui that can be extended to a production setting or integrated with custom logic and apis let’s get started on creating a robust, scalable backend with minimal overhead! prerequisites a back4app account and a new back4app project getting started with back4app https //www back4app com/docs/get started/new parse app if you do not have an account, you can create one for free follow the guide above to get your project ready basic swiftui development environment you will need xcode installed on your machine and a basic swiftui or ios app project set up swift package manager or cocoapods to add the parse swift sdk parse swift sdk documentation https //github com/netreconlab/parse swift familiarity with swift and swiftui if you’re new to swiftui, review apple’s swiftui documentation https //developer apple com/documentation/swiftui before starting make sure these are all in place before you begin having your back4app project set up and your local swiftui environment ready will help you follow along more easily step 1 – setting up back4app project create a new project the first step in building your swiftui backend on back4app is creating a new project if you have not already created one, follow these steps log in to your back4app account click the “new app” button in your back4app dashboard give your app a name (e g , “swiftui backend tutorial”) once the project is created, you will see it listed in your back4app dashboard this project will be the foundation for all backend configurations discussed in this tutorial connect the parse swift sdk back4app relies on the parse platform to manage your data, provide real time features, handle user authentication, and more connecting your swiftui application to back4app involves installing the parse swift sdk and initializing it with the credentials from your back4app dashboard retrieve your parse keys in your back4app dashboard, navigate to your app’s “app settings” or “security & keys” section to find your application id and client key (or javascript key) you’ll also find the parse server url (often in the format https //parseapi back4app com ) install the parse swift sdk if using swift package manager , open your project in xcode and then file → add packages → enter the url https //github com/netreconlab/parse swift git choose “up to next major” from the version rules and confirm if using cocoapods pod 'parseswiftog' initialize parse in your app for example, in your app struct @main struct myapp app { init() { do { try await parseswift initialize( applicationid "your app id", clientkey "your client key", serverurl url(string "https //parseapi back4app com")! ) } catch { print("error initializing parse \\(error)") } } var body some scene { windowgroup { contentview() } } } by completing this step, you have established a secure connection between your swiftui front end and the back4app backend all requests and data transactions are handled by the parse swift sdk, reducing the complexity of manual rest or graphql calls (though you can still use them when needed) step 2 – setting up the database saving and querying data with your back4app project set up and the parse swift sdk integrated, you can now start saving and retrieving data below is a simple parseobject example suppose we have a todo struct import parseswift struct todo parseobject { // parseobject conformance var objectid string? var createdat date? var updatedat date? var acl parseacl? var originaldata data? // custom properties var title string? var iscompleted bool? } saving a new todo func createtodoitem(title string, iscompleted bool) async { var todo = todo() todo title = title todo iscompleted = iscompleted do { let savedtodo = try await todo save() print("todo saved successfully \\(savedtodo)") } catch { print("error saving todo \\(error)") } } querying all todos func fetchtodos() async { do { let todos = try await todo query() find() print("fetched todos \\(todos)") } catch { print("error fetching todos \\(error)") } } alternatively, you can use back4app’s rest api endpoints, or graphql curl x post \\ h "x parse application id your application id" \\ h "x parse rest api key your rest api key" \\ h "content type application/json" \\ d '{"title" "buy groceries", "iscompleted" false}' \\ https //parseapi back4app com/classes/todo graphql mutation { createtodo(input { fields { title "clean the house" iscompleted false } }) { todo { objectid title iscompleted } } } having multiple options (parse swift sdk, rest, graphql) lets you choose the approach that works best for your workflow schema design and data types by default, parse allows schema creation on the fly , but you can also define your classes in the back4app dashboard for more control navigate to the “database” section in your back4app dashboard create a new class (e g , “todo”) and add relevant columns, such as title (string) and iscompleted (boolean) back4app supports various data types string , number , boolean , object , date , file , pointer , array , relation , geopoint , and polygon you can choose the appropriate type for each field back4app also provides an ai agent that can help you design your data model open the ai agent from your app dashboard describe your data model in simple language (e g , “please create a new todo class schema ”) let the ai agent generate the schema for you relational data if you have relational data—say, a category object that points to multiple todo items—you can use pointers or relations in parse for instance struct category parseobject { var objectid string? var createdat date? var updatedat date? var acl parseacl? var originaldata data? var name string? } struct todo parseobject { var objectid string? var createdat date? var updatedat date? var acl parseacl? var originaldata data? var title string? var category pointer\<category>? } func createtodowithcategory(categoryid string, title string) async { var todo = todo() todo title = title // construct pointer let categorypointer = pointer\<category>(objectid categoryid) todo category = categorypointer do { try await todo save() } catch { print("error creating todo with category relationship \\(error)") } } when querying, you can also include pointer data let query = todo query() include("category") do { let todoswithcategory = try await query find() print("todos with category \\(todoswithcategory)") } catch { print("error fetching todos \\(error)") } live queries for real time updates, back4app provides live queries in your swiftui app, you can subscribe to changes in a specific class enable live queries in your back4app dashboard under server settings subscribe in code // example snippet using the parse swift subscription system task { let subscription = try todo query() subscribecallback() // react to events for await event in subscription { switch event { case entered(let todo) print("new todo entered \\(todo)") case updated(let todo) print("todo updated \\(todo)") case left(let todo) print("todo deleted or left subscription \\(todo)") default break } } } whenever a todo is created, updated, or deleted on the server, your app gets notified in real time this feature is very handy for collaborative or dynamic apps that require immediate data syncing step 3 – applying security with acls and clps back4app security mechanism back4app provides access control lists (acls) and class level permissions (clps) for robust data security these let you restrict who can read or write data on a per object or per class basis, ensuring only authorized users can modify your data access control lists (acls) an acl is applied to individual objects for example, to ensure only a particular user can read/write a todo func createprivatetodo(title string, user user) async { var todo = todo() todo title = title var acl = parseacl() // grant read/write to the owner only acl setreadaccess(true, for user) acl setwriteaccess(true, for user) todo acl = acl do { let saved = try await todo save() print("private todo saved \\(saved)") } catch { print("error saving private todo \\(error)") } } class level permissions (clps) clps govern an entire class’s defaults, such as whether the class is publicly readable or writable, or if only certain roles can access it go to the back4app dashboard and select your app open the database section, select a class (e g , todo ) open the class level permissions tab configure defaults like “requires authentication” or “no access ” these permissions set a broad baseline, while acls let you fine tune security at the object level combining both ensures a strong security model for more detail, see app security guidelines https //www back4app com/docs/security/parse security step 4 – writing and deploying cloud functions cloud code allows you to run custom server side swift (or javascript) code without managing servers it’s ideal for adding business logic, data validations, triggers, or backend integrations that should not run from the client how it works write your cloud code in a file like main js (javascript) or leverage the swift based cloud code environment deploy to your back4app project the code runs in parse server’s environment, so you don’t need to maintain your own server call your cloud code from the client via the swift sdk, rest, or graphql typical use cases business logic complex data validations, field calculations, or external integrations data triggers execute logic when an object is saved, updated, or deleted security protect sensitive operations from the client by running them on the server side example function below is a sample javascript cloud code (since cloud code primarily uses js on back4app) that calculates text length main js parse cloud define('calculatetextlength', async (request) => { const { text } = request params; if (!text) { throw new error('no text provided'); } return { length text length }; }); deploying via the cli install the back4app cli https //www back4app com/docs/local development/parse cli configure your account key b4a configure accountkey deploy cloud code b4a deploy calling your function from swift struct cloudfunction { static func calculatetextlength(text string) async throws > int { do { if let result = try await parsecloud callfunction("calculatetextlength", with \["text" text]) as? \[string any], let length = result\["length"] as? int { return length } } catch { throw error } return 0 } } task { do { let len = try await cloudfunction calculatetextlength(text "hello back4app") print("text length \\(len)") } catch { print("error calling cloud function \\(error)") } } via rest curl x post \\ h "x parse application id your app id" \\ h "x parse rest api key your rest api key" \\ h "content type application/json" \\ d '{"text" "hello back4app"}' \\ https //parseapi back4app com/functions/calculatetextlength step 5 – configuring user authentication user authentication in back4app back4app uses the parseuser class to handle secure authentication password hashing, session tokens, and data are handled automatically, letting you focus on the app’s logic setting up user authentication sign up a new user struct user parseuser { var objectid string? var createdat date? var updatedat date? var acl parseacl? var originaldata data? // required fields var username string? var email string? var emailverified bool? var password string? var authdata \[string \[string string]?]? } func signupuser(username string, password string, email string) async { var newuser = user() newuser username = username newuser password = password newuser email = email do { try await newuser signup() print("user signed up successfully!") } catch { print("error signing up user \\(error)") } } log in an existing user func loginuser(username string, password string) async { do { let user = try await user login(username username, password password) print("user logged in \\(user)") } catch { print("error logging in user \\(error)") } } session tokens are handled automatically by parse you can log out func logout() async { do { try await user logout() print("user logged out ") } catch { print("error logging out \\(error)") } } social login integration integrations with google , apple , facebook , etc , are possible with additional setup check the social login docs https //www back4app com/docs/platform/sign in with apple for more details email verification and password reset enable email verification in your back4app dashboard, and configure password reset emails so users can securely recover their accounts for password resets try await user passwordreset(email "user\@example com") step 6 – handling file storage uploading and retrieving files parse includes parsefile for handling file uploads func uploadimage(filedata data) async { let parsefile = parsefile(name "photo jpg", data filedata) do { let savedfile = try await parsefile save() print("file saved at \\(savedfile url ?? "no url")") } catch { print("error uploading file \\(error)") } } attach it to a parseobject struct photo parseobject { var objectid string? var createdat date? var updatedat date? var acl parseacl? var originaldata data? var imagefile parsefile? } func createphotoobject(filedata data) async { var photo = photo() photo imagefile = parsefile(name "image jpg", data filedata) do { = try await photo save() } catch { print("error saving photo object \\(error)") } } file security by default, files are accessible via a public url you can configure file security using parse server settings https //www back4app com/docs/platform/file storage for stricter file controls, ensure only authenticated users or specified roles can upload or retrieve files step 7 – scheduling tasks with cloud jobs cloud jobs allow you to schedule and run recurring tasks like cleaning data or sending emails // main js (javascript cloud code) parse cloud job('cleanupoldtodos', async (request) => { const todo = parse object extend('todo'); const query = new parse query(todo); const now = new date(); const thirty days = 30 24 60 60 1000; const cutoff = new date(now thirty days); query lessthan('createdat', cutoff); try { const oldtodos = await query find({ usemasterkey true }); await parse object destroyall(oldtodos, { usemasterkey true }); return `deleted ${oldtodos length} old todos `; } catch (err) { throw new error('error during cleanup ' + err message); } }); after deployment, schedule it via the back4app dashboard under server settings > background jobs step 8 – integrating webhooks webhooks let your back4app app send http requests to external services (like stripe) whenever certain events occur this is helpful for hooking into third party tools or other server side integrations go to webhooks in your back4app dashboard > more > webhooks add an endpoint (e g , https //your service com/webhook ) configure which events (e g , new record in the todo class) will trigger the webhook for example, you could send a slack message whenever a user creates a new todo this helps you keep external services in sync with your back4app data step 9 – exploring the back4app admin panel the back4app admin app is a web based management interface for non technical users to do crud operations on your data it provides a user friendly ui that’s separate from the parse dashboard, making it easier to manage data in production enabling the admin app go to your app dashboard > more > admin app and click “enable admin app ” create an admin user , which auto generates an admin role and associated classes choose a subdomain for the admin interface, then log in to manage your data via a simple point and click ui conclusion by following this comprehensive guide, you have learned how to build a backend for swiftui using back4app and the parse swift sdk how to store data securely with custom class schemas and relationships how to integrate real time queries (live queries) for immediate data updates how to apply security measures using acls and clps to protect and manage data access how to run business logic via cloud code how to handle file storage , authentication, and scheduling background tasks with cloud jobs how to integrate your app with external services using webhooks with these skills, you can build an ios app or web app that’s easy to manage, secure, and ready to scale explore more advanced features—like role based permissions, push notifications, or advanced caching you can also integrate other apis or tailor your cloud code to suit specialized use cases happy coding , and enjoy building awesome apps on back4app! next steps production ready swiftui app extend this backend to handle more complex data models, caching, and performance enhancements advanced features dive deeper into specialized authentication, role based access, or third party api integrations (like stripe) explore back4app’s official docs for deeper dives on server side security, logs analysis, and advanced database tuning check additional tutorials real time chat, location based services, or multi tenant applications—combine the methods learned here with external apis to create sophisticated, real world solutions