How to send images on Parse without using a query? - ios

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;
}

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.

Firebase storage url for tableview image

I am migrating across my backend from Parse :'( to Firebase and am having some issues understand Firebase's implementation around assets and referencing them.
Essentially I need to have a JSON structure detailing some articles, each of these articles will have an image. Currently the JSON is manually added in order for the app to reference the latest articles. The images for this are manually uploaded to the storage aspect of Firebase and the file name of this is added to the JSON of the articles.
My app calls the JSON in order to populate a table view with a label for the heading of the article and an image in the same cell.
The problem I am having is retrieving the image URL for the storage assets in order to load the image into the tableview -
First I call the data of the article from the database
FIRDatabaseReference *ref = [[FIRDatabase database] reference];
[[ref child:#"articles"] observeSingleEventOfType:FIRDataEventTypeValue withBlock:^(FIRDataSnapshot * _Nonnull snapshot) {
NSArray *articles = (NSArray *)snapshot.value;} withCancelBlock:^(NSError * _Nonnull error) {
NSLog(#"%#", error.localizedDescription);
}];
From the return snapshot is converted into a model object - where the article heading is set to the model object as well as the image URL generated
Article *article = [Article new];
article.title = [articleObj valueForKey:#"title"];
if ([articleObj objectForKey:#"image"] != [NSNull null]) {
// Points to the root reference
FIRStorageReference *storageRef = [[FIRStorage storage] referenceForURL:#"gs://project-3229518851181635221.appspot.com"];
// Points to "images"
FIRStorageReference *imagesRef = [storageRef child:#"articleImages"];
// Note that you can use variables to create child values
FIRStorageReference *imagePath = [imagesRef child:articleObj[#"image"]];
if (imagePath){
article.imageURL = [NSURL URLWithString:imagePath.fullPath];
// Fetch the download URL
[imagePath downloadURLWithCompletion:^(NSURL *URL, NSError *error){
if (error != nil) {
// Handle any errors
NSLog(#"**ERROR %#", error.description);
NSLog(#"**ERROR %#", URL.absoluteString);
NSLog(#"**ERROR %#",article.title);
} else {
article.imageURL = URL;
}
}];
}
The problem I have with this method (apart from it feeling like a lot of code for something which feels like it should be a standard property) is that the Article title is available immediately, but the 'downloadURL' block takes longer, so I either need to observe when this finishes and not reload my table until each article has finished obtaining its Image URL
SO the question:
Is there an alternative non-blocking way to obtain the image URL
Or is the URL reference I see in the storage portal for the URL reliable enough to use in my JSON instead of a reference to the image name (so store the URL in my DB rather than the image name)
Also for reference, I am using SDWebimage for lazyloading images, but the URL is currently not present the first time the tablereloads due to the above-mentioned delays in retrieving the URL
Thanks in advance!
You can convert your three lines of code to single line by replacing these,
// Points to the root reference
FIRStorageReference *storageRef = [[FIRStorage storage] referenceForURL:#"gs://project-3229518851181635221.appspot.com"];
// Points to "images"
FIRStorageReference *imagesRef = [storageRef child:#"articleImages"];
// Note that you can use variables to create child values
FIRStorageReference *imagePath = [imagesRef child:articleObj[#"image"]];
to
// Points to the root reference
FIRStorageReference *storageRef = [[FIRStorage storage] referenceForURL:#"gs://project-3229518851181635221.appspot.com/articleImages/image"]];
Base on your requirement there is one extended class for SDWebImage which just takes reference of FIRStorageReference and downloads your image.
See below code for same:
FIRStorageReference *storageRef = [[FIRStorage storage]
referenceWithPath:[NSString stringWithFormat:#"/folder/images/%#",aDictCardData[#"url"]]];
[cell.imgDetail sd_setImageWithStorageReference:storageRef
placeholderImage:nil
completion:^(UIImage *image,
NSError *error,
SDImageCacheType
cacheType,
FIRStorageReference *ref) {
if (error != nil) {
NSLog(#"Error loading image: %#", error.localizedDescription);
}
}];
In above code you can find sd_setImageWithStorageReference method with storageRef to easily access FireBase Image.
You can find this Extended Class file from Here:
https://github.com/firebase/FirebaseUI-iOS/tree/master/FirebaseStorageUI
Add These classes to your project and use this method.
Hope this will helps you to get FireBase Image without getting NSURL of that image.

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)

Caching PFFile data from Parse

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....!

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