{"id":27370233,"url":"https://github.com/datastaxdevs/workshop-ios-swift-astra","last_synced_at":"2026-02-12T11:39:05.208Z","repository":{"id":45750553,"uuid":"514374005","full_name":"datastaxdevs/workshop-IOS-Swift-Astra","owner":"datastaxdevs","description":"Sample IOS app in Swift that connects to Datastax Astra","archived":false,"fork":false,"pushed_at":"2022-10-06T18:18:36.000Z","size":16661,"stargazers_count":2,"open_issues_count":0,"forks_count":2,"subscribers_count":7,"default_branch":"main","last_synced_at":"2023-03-04T04:05:52.709Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Swift","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/datastaxdevs.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2022-07-15T18:51:36.000Z","updated_at":"2022-08-17T16:28:11.000Z","dependencies_parsed_at":"2023-01-19T14:02:41.901Z","dependency_job_id":null,"html_url":"https://github.com/datastaxdevs/workshop-IOS-Swift-Astra","commit_stats":null,"previous_names":[],"tags_count":null,"template":null,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/datastaxdevs%2Fworkshop-IOS-Swift-Astra","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/datastaxdevs%2Fworkshop-IOS-Swift-Astra/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/datastaxdevs%2Fworkshop-IOS-Swift-Astra/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/datastaxdevs%2Fworkshop-IOS-Swift-Astra/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/datastaxdevs","download_url":"https://codeload.github.com/datastaxdevs/workshop-IOS-Swift-Astra/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248688195,"owners_count":21145762,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2025-04-13T08:48:30.705Z","updated_at":"2026-02-12T11:39:00.175Z","avatar_url":"https://github.com/datastaxdevs.png","language":"Swift","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Sample Swift IOS app using Datastax Astra's Document API\n\n### Contributor:\n[Victor Micha](https://github.com/vmic2002), Datastax Polaris Intern\n\n### Objective:\nBuild an app in Swift that connects to the Datastax Astra Database. By replicating this project, you will have an IOS app with fully functional backend and frontend.\n\n## Materials for the Session\n\nIt doesn't matter if you join our workshop live or you prefer to work at your own pace,\nwe have you covered. In this repository, you'll find everything you need for this workshop:\n\n- [Workshop Video/Youtube Link](https://www.youtube.com/watch?v=U2R-6gKeXXk)\n- [Slide deck](Slides/workshop-Swift-IOS-Astra.pdf)\n- [Discord chat](https://dtsx.io/discord)\n- [Questions and Answers](https://community.datastax.com/)\n- [Code for the workshop](https://gist.github.com/vmic2002/68bdfb71a55a1410ba0e708a81b24af1)\n\n## About:\nThis sample app is coded in Swift and was developed on the Xcode IDE. It connects to the Astra DB using the Document API. It handles user accounts (signing up, signing in, changing password and deleting accounts) as well as manually entering an order, taking a picture of the receipt to post an order, and seeing all past orders.\n\nGroceryHandler is an application for facilitating the accounting of splitting expenses with others. For example, if roommates buy groceries together in one order, this app would be able to indicate how much each person owes the buyer.\n\n## For beginners:\n\nIf you are new to databases, [click here](https://github.com/datastaxdevs/workshop-IOS-Swift-Astra#for-beginners-to-databases).\nIf you are new to the Document API, [click here](https://github.com/datastaxdevs/workshop-IOS-Swift-Astra#intro-to-document-api).\n\n## Prerequisites:\n1. [Download Xcode](\nhttps://developer.apple.com/xcode/).\nThe Xcode version for this application is version 13.4.1.\nIt will take a while to download. While this is happening, move on to the next step.\n2. [Create an Astra database account:](https://auth.cloud.datastax.com/auth/realms/CloudUsers/login-actions/registration?client_id=auth-proxy\u0026tab_id=sbXNIWyPYDw\u0026redirect_uri=https://astra.datastax.com/welcome)\n![](READMEPictures/Screen%20Shot%202022-07-13%20at%2011.08.20%20AM.png)\n3. After verifying the account, click on *Create Database*:\n![](READMEPictures/Screen%20Shot%202022-07-13%20at%2010.52.43%20AM.png)\n4. Enter a database name, keyspace name, and region. Name them whatever you like. For the sample app, the keyspace is named *gh_orders_userinfo*. Then click on *Create Database*\n![](READMEPictures/Screen%20Shot%202022-07-13%20at%2010.57.15%20AM.png)\n5. Click on *Go To Database*\n![](READMEPictures/Screen%20Shot%202022-07-13%20at%2011.01.41%20AM.png)\n6. In the dashboard, click on the *Connect* tab:\n![](READMEPictures/Screen%20Shot%202022-07-13%20at%2011.04.35%20AM.png)\n7. Create an application token:\n![](READMEPictures/Screen%20Shot%202022-07-13%20at%2011.09.38%20AM.png)\n8. Select the role *Administrator User* then click on *Generate Token*\n![](READMEPictures/Screen%20Shot%202022-07-13%20at%2011.20.17%20AM.png)\n9. Make sure to copy the *Token* somewhere for later\n![](READMEPictures/Screen%20Shot%202022-07-13%20at%2011.23.58%20AM.png)\n\n\u003e **⚠️ Important**\n\u003e ```\n\u003e The instructor will show you on screen how to create a token \n\u003e but will have to destroy to token immediately for security reasons.\n\u003e ```\n\n\n## How to replicate the project:\n\nSee -\u003e [Prerequisites first](https://github.com/datastaxdevs/workshop-IOS-Swift-Astra#prerequisites)\n\nGo to the directory where you would like your project to reside. If you are not sure what this means, open your Terminal app:\n\n![](READMEPictures/Screen%20Shot%202022-07-18%20at%203.18.37%20PM.png)\n\nIf you want your project to reside in your `Desktop` sub-directory for example, run (run means type this command in your terminal window):\n\n```bash\ncd Desktop\n```\n\nClone the project by running:\n\n```bash\ngit clone https://github.com/datastaxdevs/workshop-IOS-Swift-Astra.git\n```\n\nThis is all that is needed to strictly connect to the database. However, the sample app uses ML Kit Text Recognition API to decipher prices from receipts. \n\nThe Pods required for this are way too big to be stored on Github, so either follow the steps to integrate them in your project by [clicking here](https://github.com/datastaxdevs/workshop-IOS-Swift-Astra#integrate-pods-in-project) or remove them from project by [clicking here](https://github.com/datastaxdevs/workshop-IOS-Swift-Astra#remove-pods-from-project).\n\n#### Integrate Pods in Project:\n\n1. In the same window, go to your project directory by running \n\n```bash\ncd workshop-IOS-Swift-Astra\n```\n\n2. To install CocoaPods, run (if a password is required, use the one you use to log in to your laptop):\n\n```bash\nsudo gem install cocoapods\n```\n\n3. To install the Pods directory, run:\n\n```bash\npod install\n```\n\nNow the pods are installed and the project will build once opened on Xcode!\n\n#### Remove Pods from project:\n1. After cloning the git repo, go to your project directory by running:\n\n```bash\ncd workshop-IOS-Swift-Astra\n```\n\n2. Run these commands to remove the pods from the project (if a password is required, use the one you use to log in to your laptop):\n\n```bash\nsudo gem install cocoapods-deintegrate cocoapods-clean\npod deintegrate\npod cache clean --all\nrm Podfile\n```\n\n3. Make sure to comment out the whole *MLTextRecognizer.swift* file once you are in Xcode because the import statements will cause problems if the Pods were deleted successfully. Also comment out this line in the *PictureReceipt.swift* file:\n\n```swift\nprices = try await getPricesAsArray(image: image)\n```\n\n### !! Whether you choose to remove the Pods or keep them, now follow the steps below !!\n\n\n1. Launch the Xcode app and select *Open a project or file*\n![](READMEPictures/Screen%20Shot%202022-06-30%20at%204.45.29%20PM.png)\n\n2. Click on the *GroceryHandler.xcworkspace* file and select *Open*\n![](READMEPictures/Screen%20Shot%202022-07-18%20at%2011.24.10%20AM.png)\n\n3. Now make sure the project builds successfully by doing \u003ckbd\u003ecommand\u003c/kbd\u003e + \u003ckbd\u003eB\u003c/kbd\u003e in Xcode.\n\n4. To test the app, you will have to change the environment variables in Xcode and create the collections *orders* and *userInfo*. The instructions can be found [here](https://github.com/datastaxdevs/workshop-IOS-Swift-Astra#how-to-connect-to-your-own-database-in-the-app).\n\n5. Make sure that the app will run on the iPhone 13 Pro Simulator:\n![](READMEPictures/Screen%20Shot%202022-07-19%20at%201.36.11%20PM.png)\n\n6. Build the project and run the app by clicking the big play button at the top left of the Xcode window or by doing \u003ckbd\u003ecommand\u003c/kbd\u003e + \u003ckbd\u003eR\u003c/kbd\u003e.\nAn iPhone Simulator window should pop up:\n![](READMEPictures/Screen%20Shot%202022-07-20%20at%2011.20.18%20AM.png)\n\n[Click here](https://developer.apple.com/documentation/xcode/running-your-app-in-the-simulator-or-on-a-device) or [here](https://www.twilio.com/blog/2018/07/how-to-test-your-ios-application-on-a-real-device.html) to run it on your personal device instead. You will need a [cable that connects to your laptop](https://www.apple.com/shop/product/MQGH2AM/A/usb-c-to-lightning-cable-2-m).\n\nIf you get an error when trying to sign in, create an account, delete an account, or change password, it may be because you missed step 4. Make sure to finish that step before testing the app.\n\nThat's it! You can now create accounts and post orders to your database! If you would like to populate your database with fake accounts and random orders, uncomment the DEV button in the *ContentView.swift* file by removing the */** and **/* that surrounds this code:\n```swift\nButton(\"DEV\"){\n    print(\"DEV\")\n    //This is where you can test functions by running the app and clicking on this button\n    Task{\n        await populateUserInfoDB()\n        await populateOrdersDB(numNewOrders: 300)\n    }\n}\n.buttonStyle(CustomButton(color:Color(red: 0, green: 0, blue: 0.5)))\n.padding(.all, 20)\n```\nRun the app on your phone and click this button!\n                     \n\n\n## How to connect to your own database in the app:\n\nIf you would like to connect to your Astra DB from this app, you will need to change these environment variables in Xcode: `ASTRA_DB_ID`, `ASTRA_DB_REGION`, `ASTRA_DB_TOKEN`, and `ASTRA_DB_KEYSPACENAME`.\n\nThe *ASTRA_DB_ID* can be found in the dashboard of the astra website:\n![](READMEPictures/Screen%20Shot%202022-07-13%20at%204.17.34%20PM.png)\n\nTo change the values of the environment variables in Xcode, first click on *Edit Scheme...*\n![](READMEPictures/Screen%20Shot%202022-07-13%20at%209.25.48%20AM.png)\n\nThis will open the following window in which you can change the values of the environment variables:\n![](READMEPictures/Screen%20Shot%202022-07-15%20at%204.11.06%20PM.png)\n\nThe app accesses the environment variables in the *GroceryHandlerApp.swift* file:\n```swift\n//environment variables https://blog.eidinger.info/use-environment-variables-from-env-file-in-a-swift-package\npublic var ASTRA_DB_ID:String? {\n    ProcessInfo.processInfo.environment[\"ASTRA_DB_ID\"]\n}\npublic var ASTRA_DB_REGION:String? {\n    ProcessInfo.processInfo.environment[\"ASTRA_DB_REGION\"]\n}\npublic var ASTRA_DB_TOKEN:String? {\n    ProcessInfo.processInfo.environment[\"ASTRA_DB_TOKEN\"]\n}\npublic var ASTRA_DB_KEYSPACENAME:String? {\n    ProcessInfo.processInfo.environment[\"ASTRA_DB_KEYSPACENAME\"]\n}\n```\nXcode sets up the environment variables, which means that the app can only be run from Xcode. Once you run it on your phone once, the icon will still be in your phone even when it isn't connected to your computer anymore. However, if you click the icon and try to log in or post orders, the app will crash because the environment variables will not be set up.\n\n\n#### Now you should create your own collection using Swagger UI:\n![](READMEPictures/Screen%20Shot%202022-06-30%20at%204.46.48%20PM.png)\n\nYou can access Swagger UI from the Astra website:\n![](READMEPictures/Screen%20Shot%202022-07-13%20at%204.39.36%20PM.png)\n\nTo create an empty collection named *newCol* in *keyspacename1* for example:\n![](READMEPictures/Screen%20Shot%202022-07-13%20at%209.48.09%20AM.png)\n\nThe collections for the sample app are named: *userInfo* and *orders*. They are both in the keyspace *gh_orders_userinfo*. If you want to customize the app by creating different collections, make sure to change using search and replace (in the *DBController.swift* file) the *userInfo* and *orders* to whatever you named them.\n\nIf you just want to test the app, you will have to create both of these collections in whatever keyspace you created.\n\nThe JSON to create the collection *userInfo* is the following:\n\n```json\n{\"name\":\"userInfo\"}\n```\nThe JSON to create the collection *orders* is the following:\n\n```json\n{\"name\":\"orders\"}\n```\n\n### Creating your own model\nTo customize your app, you will need to come up with a model of what the data will look like in the database.\nHere is what the model looks like for a *UserInfo*: (this can be found in the *GroceryHandlerApp.swift* file)\n\n```swift\nstruct UserInfo : Codable {\n    let userName : String\n    let password : String\n}\n```\n\nHere is what the model looks like for an order:\n\n```swift\nstruct Order : Codable {\n    let userName : String\n    let receipt : [Item]\n    var paid : Bool\n    let time : String\n}\n\nstruct Item : Codable {\n    let price : Double\n    let users : [String]\n}\n```\n\nThe *Codable* makes it so that instances of these structs can be converted to JSON data objects, which is needed to post them to the database.\nTo be explicitly clear, an *Order* is posted to the collection *orders* and a *UserInfo* is posted to the collection *userInfo*.\n\n## Additional Information\n\n### For beginners to Swift: \n[Click here](https://developer.apple.com/tutorials/swiftui)\n\n### Interested in using the ML in your own app?\n\n[Click here](https://developers.google.com/ml-kit/vision/text-recognition/ios) and/or look at the *MLTextRecognizer.swift* file\n\n### Intro to Document API\n\nUsing the Document API for Astra means that data is stored in *keyspaces*. A *keyspace* can have multiple *collections* and a *collection* stores a list of *JSON documents*.\n\nThe picture below gives a graphical view of how data is stored for this sample app. There is only one *keyspace* and two *collections*. A JSON doc can be identified by its orange color.\n\n![](READMEPictures/Screen%20Shot%202022-08-08%20at%202.32.24%20PM.png)\n\nCheck out the [Astra DB documentation](https://docs.datastax.com/en/astra/docs/develop/dev-with-doc.html) for more information.\n\n### For beginners to databases:\nThe following will help you become comfortable with HTTP requests, URLs, and JSON.\n\nFirst off, what does HTTP stand for? From [CodeAcademy](https://www.codecademy.com/article/http-requests):\n\n```\n\"HTTP stands for Hypertext Transfer Protocol and is used to structure requests and responses over the internet.\nHTTP requires data to be transferred from one point to another over the network.” \n```\n\nThe HTTP request methods that we will be using in this app are GET, POST, PATCH, and DELETE.\nGET and DELETE are self explanatory. POST is used to persist data to the database and PATCH is used to update data that is already in the database.\n\nTo connect to Datastax astra using the Document API, a specific URL, which includes the database specific properties is needed as below:\n\n```\nhttps://ASTRA_DB_ID-ASTRA_DB_REGION.apps.astra.datastax.com/api/rest/v2/namespaces/ASTRA_DB_KEYSPACENAME/collections/{collection-id}\n```\n\nThe *api/rest* in the URL is what triggers the Document API. There are other methods of access (including CQL, GraphQL, etc.)\n\nThis URL might be followed by something called a *Query String*. The URL and query string are separated by a question mark -\u003e ?\n\nWe will see an example of a query string in the examples below.\n\nHowever, an HTTP request is more than just a URL. It is a URL, headers, a request method (GET, POST, DELETE, PATCH), and depending on the request method a JSON body.\n\nWe can perform HTTP requests in the terminal app using a command line tool called cURL, or client URL.\n\nBefore using cURL, run these commands in your Terminal window so that you won't have to copy these values more than once:\n\n```bash\nexport ASTRA_DB_ID=REPLACE_ME\nexport ASTRA_DB_REGION=REPLACE_ME\nexport ASTRA_DB_TOKEN=REPLACE_ME\nexport ASTRA_DB_KEYSPACENAME=REPLACE_ME\n```\n\nMake sure the variables were properly exported by running this command:\n\n```bash\nprintenv | grep ASTRA_DB\n```\n\nOr if you want to do it one variable at a time:\n```bash\necho $ASTRA_DB_REGION\n```\n\n\nNow let's go through a few examples. \n\n#### 1. How to GET all orders (max of 20) from the collection *orders* for the username *Andy1*:\n\nNotice that the collection “orders” has to have been created in your database.\n\nRun this command in your Terminal:\n\n```bash\ncurl -X 'GET' \"https://$ASTRA_DB_ID-$ASTRA_DB_REGION.apps.astra.datastax.com/api/rest/v2/namespaces/$ASTRA_DB_KEYSPACENAME/collections/orders\"'?where=\\{\"userName\":\\{\"$eq\":\"Andy1\"\\}\\}\u0026page-size=20' -H 'accept: application/json' -H \"X-Cassandra-Token: $ASTRA_DB_TOKEN\"\n```\n\nAs we can see, the HTTP method (GET), URL, query string, and headers (-H) are all there.\n\nThe query string is :\n\n```\nwhere=\\{\"userName\":\\{\"$eq\":\"Andy1\"\\}\\}\u0026page-size=20\n```\n\n*where* and *page-size* are parameters. The *\u0026* is a query string separator to pass multiple parameters in the URL.\n\nThe *page-size=20* is to specify that we want to GET a maximum of 20 orders (page-size cannot be greater than 20).\n\nThe header *accept: application/json* is to specify that we are expecting the format of the data to be retrieved to be in JSON format. If you are not familiar with JSON, a quick online research will be enough, it is simply a way of storing information.\n\nThe header *X-Cassandra-Token: $ASTRA_DB_TOKEN* is to specify the token generated by the person who created the database for security reasons. Only people with the token will be able to interact with the database.\n\n#### 2. How to GET the user info for the username *Andy1* in the collection *userInfo*:\nNotice that the collection *userInfo* has to have been created in your database.\n\nRun this command in your Terminal:\n\n```bash\ncurl -X 'GET' \"https://$ASTRA_DB_ID-$ASTRA_DB_REGION.apps.astra.datastax.com/api/rest/v2/namespaces/$ASTRA_DB_KEYSPACENAME/collections/userInfo\"'?where=\\{\"userName\":\\{\"$eq\":\"Andy1\"\\}\\}' -H 'accept: application/json' -H \"X-Cassandra-Token: $ASTRA_DB_TOKEN\"\n```\n\nNotice there are only 2 differences between this cURL command and the one from the first example: There is no *page-size* (since there is a max of 1 user info per person no need to specify how many docs we want to retrieve) and the collection-id is changed from *orders* to *userInfo*.\n\nThe JSON that is returned is of the following form:\n\n```json\n{\"data\":{\"ec47a067-d0a7-4f3b-8606-966aa39ce8e9\":{\"password\":\"itsdrewnow\",\"userName\":\"Andy1\"}}}\n```\n\n#### 3. How to POST a new user info with username *testUsername* and password *testPassword* in the *userInfo* collection:\n\nRun this command in your Terminal:\n\n```bash\ncurl -X 'POST' \"https://$ASTRA_DB_ID-$ASTRA_DB_REGION.apps.astra.datastax.com/api/rest/v2/namespaces/$ASTRA_DB_KEYSPACENAME/collections/userInfo\" -H 'accept: application/json' -H \"X-Cassandra-Token: $ASTRA_DB_TOKEN\" -H 'Content-Type: application/json' --data '\n    {\n        \"userName\":\"testUsername\",\n        \"password\":\"testPassword\"\n    }'\n```\n\nThe main difference between this command and the ones in the other examples is the HTTP method, which is POST.\n\nThere is also an additional header *Content-Type: application/json* which is to specify that the data to be persisted to the database is in JSON format. \n\nThe data itself is passed after the *--data*\n\nThis cURL command can be used to POST an order as well. All that has to be changed is the collection-id from *userInfo* to *orders* as well as the data itself.\n\nBy now you should be able to perform HTTP requests and interact with your Astra Database from the command line. Doing this from a Swift app is very similar so understanding the cURL commands is going to be extremely helpful.\n\nThe structs/classes needed to perform HTTP requests from a Swift app are JSONEncoder, URLRequest, and URLSession.\n\nThe [JSONEncoder](https://developer.apple.com/documentation/foundation/jsonencoder) class makes it easy to convert a struct into a JSON type which can then be posted to a collection of the Astra DB. The [URLRequest](https://developer.apple.com/documentation/foundation/urlrequest) struct encompasses the information regarding the HTTP request. This entails the URL, the HTTP method, and the HTTP headers. The [URLSession](https://developer.apple.com/documentation/foundation/urlsession) class handles actually performing the request to the server.\n\nCheck out the [Astra DB documentation](https://docs.datastax.com/en/astra/docs/develop/dev-with-doc.html) for more information and lots more examples of using cURL to connect to your database using the Document API.\n\n## The End\n\nCongratulations, you made it to the end! \n\nSee you next time!\n\n\u003e DataStax Developers\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdatastaxdevs%2Fworkshop-ios-swift-astra","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fdatastaxdevs%2Fworkshop-ios-swift-astra","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fdatastaxdevs%2Fworkshop-ios-swift-astra/lists"}