Caching PFFile data from Parse - ios

My app is a messaging style app and in it you can "tag" another user. (A bit like twitter).
Now, when this message is displayed, the avatar belonging to the person(s) who was tagged is displayed with that message.
The avatar of the user is stored as a PFFile against the PFUser object.
I'm loading it something like this...
PFImageView *parseImageView = ...
[taggedUser fetchIfNeededInBackgroundWithBlock:^(PFObject *user, NSError *error) {
parseImageView.file = user[#"avatar"];
[parseImageView loadInBackground];
}];
This all works fine.
The load if needed part of the code will most of the time not touch the network as for the majority of the time it has the user data cached.
However, the load in background part that gets the image and puts it into the image view runs every single time. There doesn't seem to be any caching on the PFFile data at all.
Even after downloading the same user's avatar numerous times it still goes to the network to get it.
Is there a way to get this data to cache or is this something I'll have to implement myself?

PFFile will automatically cache the file for you, if the previous PFQuery uses caching policy such as:
PFQuery *query = [PFQuery queryWithClassName:#"MyClass"];
query.cachePolicy = kPFCachePolicyCacheThenNetwork;
To check whether the PFFile is in local cache, use:
#property (assign, readonly) BOOL isDataAvailable
For example:
PFFile *file = [self.array objectForKey:#"File"];
if ([file isDataAvailable])
{
// no need to do query, it's already there
// you can use the cached file
} else
{
[file getDataInBackgroundWithBlock:^(NSData *data, NSError *error)
{
if (!error)
{
// use the newly retrieved data
}
}];
}
Hope it helps :)

In the end I created a singleton with an NSCache and queried this before going to Parse.
Works as a quick stop for now. Of course, it means that each new session has to download all the images again but it's a lot better now than it was.

You can cache result of PFQuery like below code..And need to check for cache without finding objects in background everytime..while retrieving the image.It has some other cache policies also..Please check attached link also..
PFQuery *attributesQuery = [PFQuery queryWithClassName:#"YourClassName"];
attributesQuery.cachePolicy = kPFCachePolicyCacheElseNetwork; //load cache if not then load network
if ([attributesQuery hasCachedResult]){
NSLog(#"hasCached result");
}else{
NSLog(#"noCached result");
}
Source:https://parse.com/questions/hascachedresult-always-returns-no
Hope it helps you....!

Related

Cannot store UIImage in NSMutableDictionary

I'm obtaining an image from Parse server, but when I receive it and store it in an NSMutableDictionary, it fails to stay there when I check it.
NSString* messageSenderId = [receivedMessage objectForKey:#"Sender Id"];
NSLog(#"messageSenderId = %#", messageSenderId);
if([self.avatarDictionary objectForKey:messageSenderId] == nil) { // avatar image for sender not yet stored
PFQuery* userQuery = [PFUser query];
[userQuery whereKey:#"objectId" equalTo:messageSenderId];
PFUser* messageSender = (PFUser *)[[messageSenderQuery findObjects] firstObject];
PFFile *avatarImage = messageSender[#"profilePictureSmall"];
[avatarImage getDataInBackgroundWithBlock:^(NSData * _Nullable data, NSError * _Nullable error) {
UIImage* storedImage = [UIImage imageWithData:data];
[self.avatarDictionary setObject:storedImage forKey:messageSender.objectId];
NSLog(#"objectForKey: %#", [self.avatarDictionary objectForKey:messageSender.objectId]);
[self.collectionView reloadData];
}];
}
When I check for the storedImage variable I can see that it is not empty. But, the NSLog reveals that there is no object for that key after I store it inside.
Sure that you can, but I would not.
Your problem can be due to the fact that you didn't initialize the mutable dictionary.
Images take a lot of memory and if you are storing a lot of images your app can be killed by the system.
A better approach could be save images locally and store the path to them in the mutable dictionary.
Or if you still want to store images in RAM, you can use NSCache. NSCache basically is a mutable dictionary, but it has a better memory management by evicting automatically resources and it is thread safe.

How to send images on Parse without using a query?

Is there a way to directly send a list of users an image using parse on Xcode? I am able to send the image using a query, but I'm worried that searching through every image that is stored in my class, matching it to the user that sent it, and then retrieving that image is going to take a while and I would like it to be there quickly.
This is the way I am currently saving the images to the database:
PFUser *currentUser = [PFUser currentUser];
NSString * username = currentUser.username;
NSData * imageData = UIImageJPEGRepresentation(myImageView.image, 1.0f);
PFFile * newImageFile = [PFFile fileWithName:#"image.jpeg" data:imageData];
PFObject * newImage = [PFObject objectWithClassName:#"Images"];
[newImage setObject:newImageFile forKey:#"imageFile"];
[newImage setObject:name forKey:#"username"];
[newImage setObject:object forKey:#"sendImageToFollowing"];
[newImage saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {}
Saving the image to Parse.com and sending a push that references that image in the push's payload is the way to go, for two reasons:
It's impossible to send more than a few kb via a push message. They are very small by design, so you have to pass a reference to something.
I'm guessing you want the image saved anyways :)
Save the image, get the objectId from Parse, send that as part of the custom push notification payload. You can create a custom dictionary and send it with your push. For more on that, see here:
https://www.parse.com/docs/ios/guide#push-notifications-customizing-your-notifications.
If you want to get the objectId very quickly, you can get it from the query itself when it succeeds:
[newImage saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
//Get the image objectId here
NSString *objectIdString = newImage.objectId;
}

Parse.com with iOS App and Objective-C code

until recently, I've always used Parse.com for data management of my app I was now working on a new project and I have some problems ....
P.S. I'm using Xcode 6
First there PFImageView, you can confirm this? at this point without consulting a PFImageView how can I draw a picture in my app? I do not understand why you can not use in my app PFImageView
Also when I do a query, previously (using the enter button on the keyboard) appeared the auto-build block of the query but now I find myself this
PFQuery *query = [PFUser query];
[query findObjectsInBackgroundWithBlock: (nullable PFArrayResultBlock (nullable) block]
What is happening to parse.com? where am I doing wrong? someone can 'give me help on this?
On the PFImageView:
Try calling – loadInBackground on in. Source
On autocompletion:
This seems to be a bug in Xcode actually. After they have implemented the "nullable" keyword, Xcode seems to be having a hard time auto generating code for the blocks you pass as arguments. That has nothing to do with Parse though.
Why don't use PFFile instead?
For loading an image from data you can do like this:
PFFile *fileImage = your_file;
[fileImage getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error) {
UIImage *image = [UIImage imageWithData:imageData];
yourImageView.image = image;
}];
And for the PFQuery replace that method with this block:
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) { }}];
or check the class reference here

Difference between uploading PFFile and PFObject

Somebody could explain me what happens when I upload something to Parse like this:
PFFile *imgFile = [PFFile fileWithName:#"Img.jpg" data:imgData];
[imgFile saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (!error) {
} else {
}
}];
If I use this solution where will be the uploaded file? In which class? How can I retrieve it? I'm a bit confused, because I'm using another solution in my projects, but this version would be better because PFFile can be saved with progressBlock.
This is the other way that I'm using, in this case it's obvious the class where I upload it.
PFFile *imgFileObject = [PFFile fileWithData:imgData];
PFObject *photo = [PFObject objectWithClassName:#"ImgClass"];
photo[#"image"] = imgFileObject;
[photo saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (!succeeded) {
...
} else {
...
}
}
}];
What's the difference between the two solution in practice?
case is using parse as a remote data storage.. kinda like treating parse as your iCloud drive or drobpox. you save a FILE
case is using parse as a remote database.. you don't save a FILE but make a new 'row' in the database (think of it as iCloud KV Store)
=> so PFFile uploaded as remote file (not a db entry thus it has no class)
=> PFObject is a database entry (that can then link to files or even contain data itself)

How to save a basic Core Data store to Parse.com?

I have looked and looked in Parse docs, SO and Google, and can not find an example of storing a plain ol' Core Data SQLite file to Parse.com. Initially I just want to store the Core Data file as a backup; eventually I want to add FTASync and then ability for others to utilize the stored Core Data file from this iOS app.
Is there an example of doing this without using a PFObject? Can someone point me to a place in the Parse docs where I can find out how to do this?
No, you cannot do this without any PFObject. Theoretically you can save backups just with
- (void)createBackupFromSQLiteStorageAtPath:(NSString*)path
{
NSString *name = [[NSDate date] description]; // for example, stringified date will act as name
PFFile *backup = [PFFile fileWithName:name contentsAtPath:path];
[backup saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error)
{
if (error)
{
// handle
}
else
{
// success
}
}];
}
But! If you want to access it from parse's fileserver you'll need to keep PFFile objects somehow (you can also store PFFile's url property - but it's hack) - and here's the case where PFObject comes to help. Assuming you have backed up your store already:
- (void)storeBackupFile:(PFFile*)file
{
PFObject *backup = [PFObject objectWithClassName:#"Backup"];
[backup setObject:file forKey:#"file"];
[backup setObject:[PFUser currentUser] forKey:#"user"];
[backup saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error)
{
if (error)
{
[backup saveEventually];
}
else
{
// success
}
}];
}
So after this you'll have Backup object in parse database, with link to backup file and user that created backup.
Some more considerations:
1) It's good to organize such backup as NSOperation subclass.
2) It's bad idea to store backups with Parse in such way. File storage on Parse is very expensive resource. Also, PFFile has local cache - your storage will be duplicated each time you make backup, so app's size will increase dramatically with often backups.

Resources