Quickstarters
Feature Overview
How to Build a Backend for iOS?
40 분
introduction in this tutorial, you’ll learn how to build a backend for ios using back4app https //www back4app com we’ll walk through integrating essential back4app features—such as database management, cloud functions, rest and graphql apis, user authentication, file storage, and real time queries (live queries)—to create a secure, scalable, and robust backend for your ios application back4app’s backend as a service offerings help reduce the complexity of setting up a server side infrastructure while speeding up development you can store data in a flexible nosql database style format, manage user accounts, add push notifications , and apply advanced access controls in a fraction of the time it would take to build a custom solution this means you can focus on improving the user experience and implementing core features, rather than worrying about server maintenance or provisioning by the end of this tutorial, you’ll have a ready made backend that can be adapted to real world scenarios, scaled to accommodate increased traffic, and expanded with more complex logic or third party services you’ll be able to deliver a reliable backend for your ios app, accelerate your development process , and enhance your overall user interface with less effort prerequisites to complete this tutorial, you will need 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 ios development environment you can develop with xcode (version 13 0 or above) install xcode https //developer apple com/xcode/ swift package manager or cocoapods for adding parse swift follow the parse swift github instructions https //github com/netreconlab/parse swift for installation details familiarity with swift and ios concepts apple’s swift documentation https //docs swift org/swift book/ if you’re new to swift or ios, review the official docs or a basic ios tutorial before starting having a functioning ios environment with xcode, along with your free back4app account, will help you follow along more smoothly step 1 – creating a new project on back4app and connecting why create a new project? a new back4app project forms the foundation of your backend development for ios it provides all the tools you need—database, apis, authentication, cloud functions—to build a backend quickly and securely walkthrough log in to your back4app account create a new app by clicking “new app” on your back4app dashboard give your app a name (for example, “ios backend demo”) once created, your new project will appear in your back4app dashboard installing the parse swift sdk and configuring keys back4app relies on the parse platform under the hood for ios, use the parse swift sdk 1\ retrieve your parse keys in the back4app dashboard, go to “app settings” or “security & keys” to find application id client key (or swift key if applicable) server url (often https //parseapi back4app com ) 2\ add the parse swift sdk if you’re using swift package manager // in package swift or xcode's swift packages package( url "https //github com/netreconlab/parse swift git", from "5 0 0" ) if you’re using cocoapods , add in your podfile pod 'parseswiftog' then run pod install 3\ initialize parse inside your appdelegate swift (or main swiftui app file), call parseswift initialize( ) with your credentials import swiftui import parseswift @main struct myapp app { init() { do { try await parseswift initialize( applicationid "your app id", clientkey "your client key", // optional serverurl url(string "https //parseapi back4app com")! ) } catch { print("error initializing parse \\\\(error)") } } var body some scene { windowgroup { contentview() } } } congratulations! your ios app is now connected to back4app, and every request or data transaction will go through parse swift automatically step 2 – setting up the database 1\ creating a data model back4app uses a schema approach where each class/table can be managed from the dashboard suppose we want to create a todo class go to “database” in your back4app console click “create a new class” , name it todo , and add columns like title (string) and iscompleted (boolean) 2\ creating a data model with the ai agent back4app’s ai agent can speed up your schema design open the ai agent in your dashboard describe your data model in plain language (e g , “make a new todo class with title and iscompleted fields”) let the ai build the schema for you automatically 3\ reading and writing data using the swift sdk with parse swift , define your data structure in code for example import parseswift struct todo parseobject { // parseobject protocol var objectid string? var createdat date? var updatedat date? var acl parseacl? var originaldata data? // custom properties var title string? var iscompleted bool? } // saving func createtodoitem(title string, iscompleted bool) async { var todo = todo() todo title = title todo iscompleted = iscompleted do { let saved = try await todo save() print("saved objectid \\\\(saved objectid ?? "")") } catch { print("error saving \\\\(error)") } } // querying func fetchtodos() async { do { let todos = try await todo query() find() print("fetched \\\\(todos count) todos") } catch { print("error fetching \\\\(error)") } } 4\ reading and writing data using rest api alternatively, you can use rest calls for instance, to create a todo 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 '{"title" "buy groceries", "iscompleted" false}' \\ https //parseapi back4app com/classes/todo 5\ reading and writing data using graphql api back4app also includes graphql support here’s a mutation example mutation { createtodo(input { fields { title "clean house" iscompleted false } }) { todo { objectid title iscompleted } } } 6\ working with live queries (optional) back4app supports real time updates through live queries for swift let subscription = try? todo query("iscompleted" == false) subscribe() subscription? handleevent({ event in switch event { case created(let newtodo) print("new todo created \\\\(newtodo)") case updated(let updatedtodo) print("todo updated \\\\(updatedtodo)") default break } }) step 3 – applying security with acls and clps 1\ overview access control lists https //www back4app com/docs/security/parse security (acls) control per object permissions, while class level permissions (clps) set defaults for entire classes 2\ steps class level permissions in the back4app dashboard, open a class (e g , todo ), then click the “security” tab you can lock down read/write to only authenticated users or roles acls in code when you save a parseobject, you can assign an acl adjust these to ensure your data is only accessed by the right users step 4 – writing cloud code functions 1\ why cloud code? cloud code is your best friend for adding server side logic to your ios app you can keep sensitive logic or validations away from the client, integrate external apis, and run background tasks on the server 2\ example function create a main js file locally (or in the online editor) with a function parse cloud define("calculatetextlength", async (request) => { const { text } = request params; if (!text) { throw "no text provided"; } return { length text length }; }); 3\ deployment use the back4app cli https //www back4app com/docs/local development/parse cli or the in dashboard cloud code > functions editor install the cli configure your account key deploy 4\ calling cloud code from ios task { do { if let result = try await parsecloud callfunction("calculatetextlength", with \["text" "hello back4app"]) as? \[string int] { print("text length \\\\(result\["length"] ?? 0)") } } catch { print("cloud code error \\\\(error)") } } 5\ using npm modules in your package json (within cloud code), list your dependencies then in main js const axios = require('axios'); parse cloud define("fetchposts", async () => { // use axios here }); step 5 – configuring authentication 1\ enable user authentication in your back4app dashboard, the user class is already provided you can set email verification, password resets, and more 2\ ios code samples sign up log in 3\ social login you can integrate social logins (google, apple, facebook) with parse swift reference the social login docs https //www back4app com/docs/platform/sign in with apple for detailed instructions step 6 – handling file storage 1\ setting up file storage upload and retrieve files such as images or documents through parse for swift struct gamescore parseobject { var objectid string? var createdat date? var updatedat date? var acl parseacl? var originaldata data? var score int? var picture parsefile? } func uploadimagedata( data data) async { var file = parsefile(name "photo jpg", data data) do { file = try await file save() print("file url \\\\(file url ?? "")") } catch { print("error uploading file \\\\(error)") } } 2\ retrieving files func fetchimage(file parsefile) async { do { let fetched = try await file fetch() print("fetched localurl \\\\(fetched localurl? absolutestring ?? "")") } catch { print("error fetching file \\\\(error)") } } 3\ security considerations you can configure file permissions in your back4app settings or in your app’s parse config file for example, restrict who can upload or delete files step 7 – email verification and password reset 1\ why verification? email verification ensures a user owns the email address provided password reset flows let users securely recover accounts 2\ configure in back4app go to app settings > user email settings enable email verification configure the from email , email templates, and optional custom domain 3\ implementation task { do { try await user requestpasswordreset(email "johnny\@example com") print("password reset email sent") } catch { print("error resetting password \\\\(error)") } } step 8 – scheduling tasks with cloud jobs 1\ overview use cloud jobs to automate tasks such as deleting old records or sending daily notifications they run on the server side , not triggered directly by the client 2\ example parse cloud job("cleanupoldtodos", async (request) => { const todo = parse object extend("todo"); const query = new parse query(todo); // older than 30 days const cutoff = new date(date now() 30 24 60 60 1000); query lessthan("createdat", cutoff); const oldtodos = await query find({ usemasterkey true }); await parse object destroyall(oldtodos, { usemasterkey true }); return `deleted ${oldtodos length} old todos `; }); schedule this job in the back4app dashboard under server settings > background jobs to run periodically step 9 – integrating webhooks 1\ definition webhooks let your app send data to external services whenever certain events occur for example, notify a slack channel when a todo is created 2\ configuration dashboard go to more > webhooks and select “add webhook ” set endpoint e g https //my server com/webhook endpoint event trigger e g “new record in class todo ” 3\ code example parse cloud aftersave("todo", async (request) => { const { object } = request; // make an http post to an external url // containing the new todo details }); step 10 – exploring the back4app admin panel 1\ where to find it your admin panel is accessible via “more” > “admin app” in the back4app dashboard create an admin user and choose a subdomain for easy access 2\ features data browsing view and edit classes in a user friendly format logs check server logs and cloud code logs analytics monitor usage, push notifications, etc conclusion in this tutorial, you learned how to build a backend for ios using back4app and the parse swift sdk you integrated a scalable database, implemented security with acls and clps, wrote cloud code functions, configured user authentication, handled file storage, and even scheduled background tasks with these essential features in place, you can offer a reliable backend for your ios mobile application while focusing on the user experience and unique features next steps explore advanced roles and custom access controls for multi level security integrate advanced features like push notifications, geo queries, or external data sources review back4app’s official documentation for performance tips, logs analysis, or real time analytics try out additional tutorials on chat applications, iot integration, or e commerce expansions by leveraging back4app, you get an open source based platform that is a great option to reduce complexity, store data easily, and incorporate real time functionalities into your ios app implementing these steps frees you up to work on design, user flows, or business logic, creating a robust backend for your ios app in no time