Build An iOS app with MongoDB Stitch
I’m not sure why, but there’s not much resources to help out setting up MongoDB for iOS apps on the web. My first time using it was slightly frustrating — especially because the documentation was not too clear.
Hopefully, this tutorial might help some devs out there trying to learn how to use it.
What is MongoDB?
MongoDB is a document database that stores data in a ‘JSON-like’ format known as ‘BSON’ which basically stands for Binary JSON.
How will we implement it on our app?
We’ll use MongoDB Stitch which is a server-less platform that helps developers create apps without having to manually set up a server. The great thing is that it will be directly integrated with your database.
For this tutorial, we’ll run through the following steps:
- Create an iOS project & install Stitch using CocoaPods
- Create a server & stitch app on MongoDB
- Write our code & upload a document
You can clone or download the project template from here: https://github.com/danielkioko/MongoApp
Beginning the Project
- Create an Xcode project in Single View App, let’s call it MongoApp
- Close it, and open Terminal. Navigate to the project folder, and run ‘pod init’
- Run ‘open podfile’ to open the Pod-file.
- Type in
pod 'StitchSDK', '~> 6.0.0'
on a new line afteruseframeworks!
- run ‘pod install’ and when it’s done open MongoApp.xcworkspace
Setting Up MongoDB
- Next we’ll create our database with MongoDB, you’ll need an SignUp for that. PS: It’s free for your first cluster.
- Once you’ve created your Cluster, you’ll create your database and it’s first collection.
- Before we move to coding, we’ll need to create our StitchApp
- After that, On the side menu click Rules, create a rule by selecting a database. For now, don’t use a template and select Read & Write then save. Make sure to click on Review & Deploy Changes on the top bar to confirm any changes you make.
- Click on Advanced mode to make sure you can: Read, Write, Insert & Delete from your database.
Let’s Code
We’ll begin by creating our Data Model, A contact.
In AppDelegate. Swift, we’ll initialize our stitch app, then link our app with the database and collection. Notice how Mongo uses our Data Model’s class as reference to how or data should be structured.
Inside ViewController.Swift, you’ll login Anonymously with Stitch
Finally, create a new file, name it UploadViewController. Here, we’ll upload a contact right after you login.
That’s All! Run your app now 😄.
Just in-case, here’s a link to the project on GitHub: https://github.com/danielkioko/MongoApp
I hope you had fun, feel free to let me know how goes in the comments.
Happy Coding! 🌟