How to create a database using Parse that will work offline? - ios

My app is a directory with basic things like phone numbers and locations. There's going to be many entries and I will have to update the database on a weekly basis and I don't want to rely on my users to update their app using the App store, so I want the data to be updated whenever they connect to the internet, but I want all of the data stored locally so they can use it even if they don't have internet access. For my first app, it's proving to be quite tricky :)
I think I'll have to use Parse so I can update the database whenever I need to, along with something like Realm (https://realm.io/) or Core Data (hopefully not Core Data :( ). I read about Parse's Local DataStore, and if there's a way to make it work for my needs I'd definitely use it. I like the simplicity of Realm though and if I there's a way to make it work with Parse, that would be the route I'd want to take.
Can somebody show me an example on how they might go about doing this? If the PFObject or RLMObject is called person and has two strings (phone number and name, how would you get that from Parse.com to the device (local storage)?
This is an extra and I don't even know if it's possible*
While the app is downloading from the App Store, could it download the data from Parse? As in, the second the user opens the app, even if they no longer have internet access, the data is locally stored and usable to them.
(I only know Swift but may be able to understand obj-c if anybody cares to show me some code snippets)
Any help at all would be greatly appreciated :)

Joe from Realm here.
First to retreive an object from Parse you will need to do this:
var query = PFQuery(className:"GameScore")
query.whereKey("playerName", equalTo:"Sean Plott")
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
if error == nil {
// The find succeeded.
println("Successfully retrieved \(objects!.count) scores.")
// Do something with the found objects
if let objects = objects as? [PFObject] {
for object in objects {
println(object.objectId)
}
}
} else {
// Log details of the failure
println("Error: \(error!) \(error!.userInfo!)")
}
}
You can read more about this here
Once you retrieve your objects, I would loop through them as you see here
for object in objects {
println(object.objectId)
}
And then I would use Realm's Realm().create(_:value:update:)(shown in code below). You need to make sure you have a primary key to use this though (I would use parse's objectId as the primary key in Realm). Here is how you set a primary key in Realm.
An example of how I would import them into Realm would be something like this (Where Venue is the class of the way the object is stored in Realm):
let realm = Realm()
realm.write {
for object in objects {
realm.create(Venue.self, value: object, update: true)
}
}
You can read more about importing here
Lastly the logic of when you do this is up to you. You could do it each time the person opens the app. One thing with syncing local databases with the ones on the server is that it's good to just check another Table maybe called LastUpdated. This table will let you know if you need to update your local database. Overall it's a very manual process but it depends on the situation and how you want to structure your app.

Related

Realm Swift: Question about Query-based public database

I’ve seen all around the documentation that Query-based sync is deprecated, so I’m wondering how should I got about my situation:
In my app (using Realm Cloud), I have a list of User objects with some information about each user, like their username. Upon user login (using Firebase), I need to check the whole User database to see if their username is unique. If I make this common realm using Full Sync, then all the users would synchronize and cache the whole database for each change right? How can I prevent that, if I only want the users to get a list of other users’ information at a certain point, without caching or re-synchronizing anything?
I know it's a possible duplicate of this question, but things have probably changed in four years.
The new MongoDB Realm gives you access to server level functions. This feature would allow you to query the list of existing users (for example) for a specific user name and return true if found or false if not (there are other options as well).
Check out the Functions documentation and there are some examples of how to call it from macOS/iOS in the Call a function section
I don't know the use case or what your objects look like but an example function to calculate a sum would like something like this. This sums the first two elements in the array and returns their result;
your_realm_app.functions.sum([1, 2]) { sum, error in
if let err = error {
print(err.localizedDescription)
return
}
if case let .double(x) = result {
print(x)
}
}

Get list of users who liked a post Swift and Firestore

I am attempting to build a tableview that displays the users who have liked the current user's posts. For example, "John Smith, Tom Jones, and Sally Hughes liked your post (display image of post in cell". I think I'm on the right track but I'm wondering if my data structure is going to make this unnecessarily difficult or if there is an easier way.
My Firestore data structure is just below. The "BmV..." is the userId, "-M0e..." is the postId, and the "Ff0..." and "nIh..." are the users who have liked the post.
"likeActivity" : {
"BmvRlWWuGRWApqFvtT8mXQlDWzz2" : {
"-M0efUXcZy43fDVXjTvT" : {
"Ff0CxZhQzYVHuqbnsiOKwRAB01D2" : true,
"nIhx1SnChjapy4cbrD5sC1WIZXM2" : true
}
},
}
My first question is if this is the best way to structure this data? Then, In the ActivityViewController using the following code to retrieve of the current user's posts with activity.
var activityDict = [String: [Any]]()
let newActivity = DataService.ds.REF_LIKE_ACTIVITY.child("\(uid)")
//print("NEW POST - \(newPost)")
newActivity.observe(.value, with: { (snapshot) in
self.posts = []
if let snapshot = snapshot.children.allObjects as? [DataSnapshot] {
for snap in snapshot {
print("ACTIVITY -- \(snap.key)")
let userLikeData = DataService.ds.REF_LIKE_ACTIVITY.child("\(uid)").child(snap.key)
userLikeData.observe(.value, with: { (snapshot) in
self.posts.append(snap.key)
print("SNAPSHOT VALUE -- \(snapshot)")
if self.activityDict["\(snap.key)"] != nil {
self.activityDict["\(snap.key)"]!.append(snapshot.value!)
} else {
self.activityDict["\(snap.key)"] = [snapshot.value!]
}
self.activityTableView.reloadData()
})
}
}
})
My next question is if the activity should be accumulated in an array of dictionaries like I have it? Is there a better way to organize this data?
My first question is if this is the best way to structure this data?
When using NoSQL databases there is no singular "best" way to store data. You'll instead store the data in a way that best supports your use-cases. And since you'll typically uncover more (details about your) use-cases as you implement and evolve your app, you data model evolves (adapting and expanding) with it.
I recommend reading NoSQL data modeling, and watching Firebase for SQL developers and Getting to know Cloud Firestore. The last one is for Cloud Firestore, but many of the techniques Todd discusses apply equally to other NoSQL databases.
should [the activies] be accumulated in an array of dictionaries like I have it?"
If that works for your use-cases, then it sounds fine.
The only thing of note is that you're using observe, which attaches a permanent listener, and then append the updated snapshot data to the array. This means that if an activity gets changed in the database, your closure will get called again with a snapshot for that activity.
This is great, because it allows you to show the updated activity in the UI. But since you're appending it to the array, you'll end up displaying the activity twice: once as it was stored in the database when you first loaded it, and then again as it exists after the update. If that is what you're aiming for then 👍, but it is more common to update the existing data in the array, instead of adding the updated data as a new item.

Is there a way to access properties of an x-coredata:// object returned from an NSFetchRequest?

TL;DR: Is there a way to programmatically read/recall (NOT write!) an instance of a Core Data entity using the p-numbered "serial number" that's tacked on to the instance's x-coredata:// identifier? Is this a good/bad idea?
I'm using a method similar to the following to retrieve the instances of an Entity called from a Core Data data store:
var managedContext: NSManagedObjectContext!
let fetchRequest : NSFetchRequest<TrackInfo> = TrackInfo.fetchRequest()
fetchResults = try! managedContext.fetch(fetchRequest)
for (i, _) in Global.Vars.numberOfTrackButtons! {
let workingTrackInfo = fetchResults.randomElement()!
print("current track is: \(workingTrackInfo)")
The list of tracks comes back in fetchResults as an array, and I can select one of them at random (fetchResults.randomElement()). From there, I can examine the details of that one item by coercing it to a string and displaying it in the console (the print statement). I don't list the code below, but using workingTrackInfo I am able to see that instance, read its properties into other variables, etc.
In the console, iOS/Xcode lists the selected item as follows:
current track is: <MyProjectName.TrackInfo: 0x60000374c2d0> (entity:
TrackInfo; id: 0xa7dc809ab862d89d
<x-coredata://2B5DDCDB-0F2C-4CDF-A7B9-D4C43785FDE7/TrackInfo/p22>;
data: <fault>)
The line beginning with x-coredata: got my attention. It's formatted like a URL, consisting of what I assume is a UUID for the specific Core Data store associated with the current build of the app (i.e. not a stable address that you could hardcode; you'd need to programmatically look up the Core Data store, similar to the functions we use for programmatically locating the Documents Folder, App Bundle, etc.) The third item is the name of the Entity in my Core Data model -- easy enough.
But that last number is what I'm curious about. From examining the SQLite database associated with this data store, it appears to be a sort of "instance serial number" associated with the Z_PK field in the data model.
I AM NOT interested in trying to circumvent Core Data's normal mechanisms to modify the contents of a managed object. Apple is very clear about that being a bad idea.
What I AM interested in is whether it's possible to address a particular Core Data instance using this "serial number".**
In my application, where I'm randomly selecting one track out of what might be hundreds or even thousands of tracks, I'd be interested in, among other things, the ability to select a single track on the basis of that p-number serial, where I simply ask for an individual instance by generating a random p-number, tack it on to a x-coredata:// statement formatted like the one listed above, and loading the result (on a read-only basis!) into a variable for further use elsewhere in the app.
For testing purposes, I've tried simply hardcoding x-coredata://2B5DDCDB-0F2C-4CDF-A7B9-D4C43785FDE7/TrackInfo/p22 as a URL, but XCode doesn't seem to like it. Is there some other data Type (e.g. an NSManagedObject?) that allows you to set an x-coredata:// "URL" as its contents?
QUESTIONS: Has anyone done anything like this; are there any memory/threading considerations why grabbing instance names in this manner is a bad idea (I'm an iOS/Core Data noob, so I don't know what I don't know; please humor me!); what would the syntax/method for these types of statements be?
Thanks!
You are quite close.
x-coredata://2B5DDCDB-0F2C-4CDF-A7B9-D4C43785FDE7/TrackInfo/p22
is the uriRepresentation() of the NSManagedObjectID of the record.
You get this URL from an NSManagedObject with
let workingTrackInfo = fetchResults.randomElement()!
let objectIDURL = workingTrackInfo.objectID.uriRepresentation()
With this URL you can get the managed Object ID from the NSPersistentStoreCoordinator and the coordinator from the managed object context.
Then call object(with: on the context to get the object.
let persistentStoreCoordinator = managedContext.persistentStoreCoordinator!
if let objectID = persistentStoreCoordinator.managedObjectID(forURIRepresentation: objectIDURL) {
let object = managedContext.object(with: objectID) as! TrackInfo
print(object)
}

Fetching only different data from Parse

I am trying to update an array of PFObjects. In my understanding, fetchAll() (in its asynchronous derivations) is the correct method to update all the objects, as fetchAllIfNeeded() will only update the PFObjects that have no data associated with them yet. However each time fetchAll() is executed, the entire list of PFObjects is downloaded again, whether or not any change has been made. For example, if I have a list of posts, and I would like to check if any edits to the posts has been made, in every case all the posts in their entirety, (text, pictures and so on) will be downloaded, regardless of whether the text of one post was simply edited or even if there were any edits at all. There is a big difference in data consumption in downloading the text for one attribute of a PFObject and downloading a whole array of them, many including pictures, and so I would like to find a method that will only download the changes. Is this possible?
In addition, if this is possible, is there a way that I could get a list of the PFObjects that needed updating? i.e., if posts 4 and 12 needed updating out of an array of 20, how could I know this?
Thanks.
fetchAll does as it's name implies - fetches all objects. You can use a PFQuery against the updatedAt column to retrieve objects that have been updated since a certain date/time. You will need to keep track of your last update date/time locally, say using NSUserDefaults -
let query=PFQuery.queryWithclassName("MyClass")
let defaults=NSUserDefaults.standardUserDefaults()
if let lastUpdateDate=defaults.objectForKey("lastUpdateDate") as? NSDate {
q.whereKey("updatedAt",greaterThan:lastUpdateDate)
}
q.findObjectsInBackgroundWithBlock({(objects:[AnyObject]!, error: NSError!) in
if(error == nil) {
defaults.setObject(NSDate(),forKey:"lastUpdateDate")
for object in objects {
...
}
} else {
//Do something with error
}
})

Saving and loading UITableView array - iOS Swift Parse

I have the following; which fetches the data from the Parse backend and loads the class instances into a NSArray to plug into a UITableView.
var ObjectIDClass = PFQuery(className: "TestObject")
ObjectIDClass.findObjectsInBackgroundWithBlock({
(ObjectsArray : [AnyObject]?, error: NSError?) -> Void in
var ObjectIDs = ObjectsArray as! [PFObject]
for i in 0...ObjectIDs.count-1 {
self.iDArray.append(ObjectIDs[i].valueForKey("objectId") as! String)
self.NameArray.append(ObjectIDs[i].valueForKey("PDFName") as! String)
self.tableView.reloadData()
}
})
This only works with network connection and as soon as the application is closed and then reopened without network, the table is blank. What I am aiming for is to store the data in the Local Datastore and if there is no connectivity, load from the Local Datastore. I can't figure it out using pin, but sure that is how it is done. Any help would be hugely appreciated!
Instead of focusing strictly on Local Datastore, which isn't a bad thing. I just feel you are using that solely because you want to have access to that data, say when the user is in airplane mode, or when there are just low network conditions. If that is the case, then you can take advantage of Parse's built in cache system. The PFQuery cache by default is set to ignore cache. This means, none of the information incoming from the server is stored in a temp folder on the users hard disk (exactly what your looking for). So you have to explicitly tell the objects to be cached on device using one of their many caching policies
For you, this will be good:
query.cachePolicy = .CacheElseNetwork
// Results were successfully found, looking first on the
// disk and then on network.
query.findObjectsInBackgroundWithBlock {
You can review other ways to cache with these options : https://www.parse.com/docs/ios/guide#queries-caching-queries
Small side note, please don't uppercase your variables. It doesn't follow proper naming conventions. ObjectIdDClass should resemble, somewhat, what your going to do with it's class, so it should be called query or something. And ObjectsArray should be objects because you already know it's an array and you don't capitalize anything that's not a class, usually. It makes for easier reading

Resources