RealmSwiftframeworks to your project. This is most easily accomplished using using either of the major iOS dependency managers: Cocoapods or Carthage. Alternatively, you can install the framework by downloading it directly from Realm and dragging it into your Xcode project. The tabs below give detailed instructions on how to install the Realm framework for each of these options.
Podfileto track, load, and manage your project's external dependencies; to create the
Podfile, open a new terminal window, change the directory to your newly created Xcode project. Type in:
Podfile- open this file with an editor of your choice and look for the section that starts with
# Pods for iOSToDoApp, then add the following line:
iOSToDoApp.xcworkspaceto continue to work on your project.
Cartfile. You will need to create the
Cartfilein your Xcode project directory, then add the following line:
Realm.frameworkfiles from the Carthage/Build/iOS directory to the “Linked Frameworks and Libraries” section of your Xcode project’s “General” settings tab. Click OK when prompted to copy the framework files.
Realm-swift-x.y.z(where x.y.z is a version number). Open this folder, navigate to the latest swift version (at the time of this writing 4.02) and drag the
RealmSwift.Frameworkfile into the Frameworks and Libraries tab as shown here:
iOSToDoApp.xcproj(which is the default project made when you created your app) and reopen the newly-created
iOSToDoApp.xcworkspaceto be able to successfully compile with the Realm framework.
Info.plistfor your target (this will be in the iOSToDoApp group in the file navigator)
Main storyboard file base nameentry and remove it by pressing on the
-icon next to it in the property editor
Main.storyboardfile in Xcode's file navigator and delete it by selecting it and then pressing the
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?)method to match the following code below. This sets up
WelcomeViewControllerwhich we will create in an upcoming step.
File > New > File... in Xcode and then selecting "Swift File" from the file type selector panel. Press
Constantsfor the file name (the
.swiftextension will be added automatically) and navigate, if needed, to your Xcode project directory and save the file.
Constants.swift; replace the string
MY_INSTANCE_ADDRESSwith the hostname portion of the Realm Cloud instance you copied from the Realm Cloud Portal (e.g.,
mycoolapp.us1.cloud.realm.io). We will use these constants (e.g.
Constants.REALM_URL) wherever we need to reference our Realm instance.
WelcomeViewController.swift. This will be the controller you see when the app starts up and will be used to log in to the app and connect your application to the Realm Cloud.
File > New > File... in Xcode. Select "Cocoa Touch Class" from the file type selector panel. Press
next, then enter
WelcomeViewControllerfor the class name and
UIViewControllerfor the subclass name. Press
nextagain, navigate to your Xcode project directory if necessary, and save the file.
viewDidAppearmethod to the view controller with the snippet . below. The main function of this new method is to log a user in to your Realm Cloud instance. We are just going to login using a "nickname" you provide from a dialog that will be presented when the app launches.
Nicknamemethod, which we're using in this short introduction, does not require a login password, making it convenient for prototyping and extremely low-security applications. Nickname credentials are constructed with:
let creds = SyncCredentials.nickname("sally", isAdmin: true)
isAdminis set to true; this allows this user full control over the Realm. We will revisit this later, but for the purposes of getting started quickly we recommend that you keep this set to true to encounter less friction when learning more about Realm.
viewDidAppearmethod does not appear in the initial version of our WelcomeViewController: Add this new method after the closing brace of the stub
viewDidLoad()method near the top of the file:
ProjectsViewController, which we will build in the next several steps. In the event that a login attempt fails, this method will post a Realm error message dialog detailing what went wrong.
Item.swiftand add in the model definition below.
WelcomeViewController, create a new view controller by selecting
File > New > File... This time, select "Swift File" from the file type selector panel. Press
next, then enter
Itemfor the file name (the
.swiftextension will be added automatically) and navigate to your Xcode project directory (if necessary) and save the file.
timestampproperty to sort the collection of Items.
Project. Continue by creating a new Swift file called
Project.swift. This will be the model that represents a grouped collection of ToDo items.
File > New > File... and selecting "Swift File" from the file type selector panel. Press
Projectfor the file name (the
.swiftextension will be added automatically) and navigate, if needed, to the Xcode project directory for
SyncIntroand save the file.
Projectmodel , creating a new view controller is done by selecting
File > New > File... and this time selecting "Cocoa Touch Class" from the file type selector panel. Press
nextthen enter ProjectsViewController for the file name (the
.swiftextension will be added automatically) and navigate, if needed, to your Xcode project directory and save the file...
SyncConfigurationthat can be accessed from the logged in
SyncUser. The automatic sync configuration determines which sync server to contact based on the user that is currently logged in, and opts into the query-based Query-based synchronization mode. This mode tells the server not to download all of the Realm's data, but rather to only download the portion of the object graph that matches queries that the client has explicitly subscribed to.
Projectmodel records where the
ownerproperty matches the ID of the currently logged in user (
SyncUser.current!.identity!), and these will be sorted in date order, newest first.
viewDidLoadmethod as follows:
Projectin the realm database that is satisfied by our filter, which in this case is any project that belongs to the currently logged in user.
viewDidLoadmethod. This method sets up the view controller just after it is initialized. We will add more setup instructions shortly, but for now, let's just create a button handler that will add a logout button. This will allow us to test authentication and ensure that we can connect and log in to our Realm Cloud instance. Once this is ready we can add the rest of the support for adding and managing Projects and ToDo items.
logoutbutton to log out. You can repeat this and create as many accounts on your Realm Cloud instance as you like.
viewDidLoadmethod of ProjectsViewController.swift, add the following subscription:
projectsinstance variable either before this subscription executes or immediately after, the variable would not contain any data. So we will add a subscription notification to alert our app when the synchronization is complete, and we will add a results notification to tell us about the changes that are made.
AtivityIndicator. On line 14 we register a subscription notification. When the state of that subscription is
.completewe remove the
ActivityIndicatorbecause our data is synced and ready. To access this data we have registered a results notification on
projects. Any time we receive new data or edit data, we update a
UITableView, which we will implement in the next step.
changesobject is filled with fine-grained notifications about which Items were changed, including the indexes of insertions, deletions, modifications, etc.
UITableViewinstance which rows to change with the
endUpdatesmethods. Now any modifications to the
Projectobjects will trigger animations appropriately.
notificationToken. So long as the
notificationTokenexists -- which will be whenever the ProjectsViewController is on-screen -- then the observe handler will consistently be called.
deinitfor the UIViewController is a convenient place to add
notificationToken?.invalidate()method which cleans up this observer for us. Add the following
deinitmethod following after the init methods near the top of the file:
UITableViewand setting the view's title as well; to do this modify the viewDidLoad method you added earlier:
UITableViewDataSourceprotocols. We will add these to our
ItemsViewControllerjust after the
UIViewControllersubclass definition; the resulting declaration should look like this:
ProjectsViewControllerconforms to them.
UITableViewDataSource. With an ordered collection of
Results<Item>we can always see the items in the order they were created. We will begin by implementing what each cell in the
UITableViewwill look like in the
textLabelto equal the
cell.detailTextLabelwill display the current number of ToDo items that are associated with the
UITableViewDataSourcehow many projects to render; add this method after the previous one:
UITableViewthe method is called and we will navigate to the relevant
Item. We will implement the ItemViewController in step 9.
viewDidLoadmethod, just after the first button handler declaration for the logout button, add the following:
WelcomeViewController, we will present a
textFieldthat will prompt for the name of the ToDo
UITableViewDataSourceprotocol that will allow us to respond to swipes and allow deletion of Projects:
File > New > File..and then selecting "Cocoa Touch Class" from the file type selector panel. Press
next, then enter
ItemsViewControllerfor the class name and
UIViewControllerfor the subclass name. Press
nextagain, navigate to your Xcode project directory if necessary, and save the file. Add the following frameworks and class:
Projectthat was passed to the view controller.
Projectrecords in order to get only the data we need, not all the possible data that may exist inside a Realm. Try logging in as different users to see that only the desired data will be synced.
ProjectsViewController) for ToDo items. We know about (can find) these projects because of the ability to subscribe to
Projectrecords that match a specific query we are interested in. In this case projects that were created by our own user - represented by the
SyncUser.current.identitywhich is Realm's way of tracking the currently logged in user.
ProjectsViewControllerin such a way that when we tap on the row for a given project, that project record is passed over to the ItemsViewController which uses this information to show us any existing ToDo items and/or create new ones that will be added to the selected project.
Projectinstance so only the user that created it can read, modify, or delete it.
Projectto be accessible only to a single user, we need to use a separate role for each user. We can then grant the current user's role the appropriate permissions when we create a new
Project. This will have the effect of preventing all other users from seeing or modifying that
PermissionUser.role. We'll use this role when creating new projects.
permissionsattribute to the
Projectmodel. This tells Realm that we wish to configure the permissions of each
Projectinstance independently, and serves as the means for doing so.
Permissionclass represents the set of privileges we want to grant and the role to which they should be granted. Since we want to limit each
Projectto being visible to only a single user, we will grant the current user's role the appropriate permissions when we create a new
Project. This will have the result of preventing all other users from seeing or modifying the new
Projectwe now associate a new
Permissionwith it to restrict who has access to it.
Project, we prevent any other user from having access to the
everyonerole, and this role has access to all objects within the Realm. As part of lowering the default permissions, we will limit the access of this
Projecttype. This means that the only
Itemobjects that can be synchronized are those associated with a
Projectthat we have permissions to access. Additionally, we remove the ability for
everyoneto change the permissions of each of our model classes.