Can't fetch parse file from PFObject - ios

Trying to fetch a PFfile from PfObject but when I fetch value of a particular key , it only gives me a class name
Here is my CloudCode
Parse.Cloud.define("fetchBusinessWithID", function(request, response) {
var query = new Parse.Query("Business");
query.equalTo("uniqueBusinessID", request.params.businessId);
query.find({
success: function(results) {
if(results.length > 0)
{
var fetchedObject = results[0];
response.success(fetchedObject);
}
else
{
response.error("No Business Saved Yet");
}
},
error: function() {
response.error("Something Went wrong");
}
});
});
And this is on iOS
PFCloud callFunctionInBackground:#"fetchBusinessWithID"
withParameters:#{#"businessId": #"Madept2"}
block:^( PFObject *business, NSError *error) {
}];
When I see PFObject in Debug console
So how can I fetch attributes of this file, as I can not parse full object of PfFile, Please help me on this, What I am doing wrong.
Here is my data Model

Get your image data with:
PFFile *imageFile = [business objectForKey:#"aboutImage"];
[imageFile getDataInBackgroundWithBlock:^(NSData *result, NSError *error) {
if (error == nil) {
UIImage *aboutImage = [UIImage imageWithData:result];
// use your image
}
}];

Related

Error saving images to Parse: "request body stream exhausted"

I am having a problem uploading images to Parse. Things were working fine up to yesterday. My app isn't live yet I'm just testing, images are about 25kb and it's just a single image used for the user profile picture. Code is:
//Save the image
NSData *imageData = UIImageJPEGRepresentation(image, 1);
PFFile *imageFile = [PFFile fileWithName:#"profile.jpg" data:imageData];
[imageFile saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if(succeeded){
[userBank setObject:imageFile forKey:#"profilePic"];
[userBank saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if(succeeded){
NSLog(#"save done");
userBank = [PFUser currentUser];
user[#"profilePic"] = imageFile;
[userBank saveInBackground];
}
else{
NSLog(#"%#", error);
handler(NO,YES,nil);
}
}];
}
else{
NSLog(#"image not saved %#",error);
handler(NO,YES,nil);
}
}];//End save image block
I am suddenly getting this error: request body stream exhausted, NSUnderlyingError=0x17ece150 "request body stream exhausted". Has anyone encountered this before and could give me some pointers to what might be happening here?
Try this:
NSData *imageData = UIImageJPEGRepresentation(image, 1);
PFFile *imageFile = [PFFile fileWithName:#"profile.jpg" data:imageData];
[imageFile saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (!error) {
if (succeeded) {
userBank = [PFUser currentUser];
user[#"profilePic"] = imageFile;
[userBank saveInBackground];
}
} else {
// Handle error
}
}];
Seems the issue was either my connection or Parse, although I did try and reset my internet connection a number of times and it made no difference. Anyway after about 30 minutes it started working again. Just posting this incase someone else has the same issue. Parse doesn't seem that reliable...
try this
This error Comes on IOS but you can use different approach
like change your code line in formdata where you appending the file
var fd = new FormData();
fd.append("fileToUpload", document.getElementById('fileToUpload').files[0]);
to the below line basically don't append the file control but use the base64 image data
var reader = new FileReader();
reader.readAsDataURL(opmlFile.files[0]);
reader.onload = function () {
var base64DataImg = reader.result;
base64DataImg = base64DataImg.replace('data:'imagetype';base64,', '');
formData.append("FileBase64Data", base64DataImg);
}
Regards
Anil

Saving an retrieving sound on Parse.com

I am trying to download some short sound file on Parse.com in an iOS application.
The file has previously been saved using the following code:
NSData *soundData = [NSData dataWithContentsOfURL:myURL];
parse_Sound = [PFFile fileWithName:#"XXYYZZ"
data:soundData];
[parse_Sound saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (!succeeded) {
NSLog(#"sound-upload NG”);
} else {
NSLog(#"sound-upload OK");
}];
}
}];
Seeing the message on the debugging console, it appearently works.
Now what kind of code do I need to run to retrieve(download) the sound file?
I have browsed the net, but found nothing clear and working.
To get data back from the server you need to need to run a query asking for that object but you haven't associated the uploaded file with a column in any Class yet. Uploading a PFFile is iOS is a two step process:
1) Upload the PFFile to the server
2) In the callback associated the PFFile with a column in a data object
NSData *soundData = [NSData dataWithContentsOfURL:myURL];
parse_Sound = [PFFile fileWithName:#"XXYYZZ"
data:soundData];
[parse_Sound saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (!succeeded) {
NSLog(#"sound-upload NG”);
} else {
NSLog(#"sound-upload OK");
PFObject *soundStuff = [PFObject objectWithClassName:#"Sounds"];
soundStuff[#"soundFile"] = parse_Sound;
[soundStuff saveInBackground];
}];
}
}];
Now to get the data back you would run a query on the Sounds class that will have the sound data in the soundFile column:
PFQuery *query = [PFQuery queryWithClassName:#"Sounds"];
[query whereKey:#"someKey" equalTo:#"someValue"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
// The find succeeded.
// Do something with the found objects
for (PFObject *object in objects) {
NSLog(#"%#", object.objectId);
PFFile *soundFile = object[#"soundFile"];
NSData *soundData = [soundFile getData];
}
} else {
// Log details of the failure
NSLog(#"Error: %# %#", error, [error userInfo]);
}
}];
I haven't tested any of this code but it at least demonstrates the steps needed and should get you started.
Here are the examples from the documentation:
PFObject *jobApplication = [PFObject objectWithClassName:#"JobApplication"]
jobApplication[#"applicantName"] = #"Joe Smith";
jobApplication[#"applicantResumeFile"] = file;
[jobApplication saveInBackground];
Then to get the data back:
PFFile *applicantResume = anotherApplication[#"applicantResumeFile"];
NSData *resumeData = [applicantResume getData];
Notice that file is being associated with the applicantResumeFile column of the JobApplication class so that the file data can be retrieved in queries.
You need to keep a reference to that file somewhere (ideally in a column of the PFObject it belongs to).
If you don't keep a reference you're out of luck and you can't retrieve already uploaded files that have no association to any object.
I suggest you read through the Parse documentation for files on iOS https://www.parse.com/docs/ios_guide#files/iOS

PFObject won't save PFFile PArse

I can't seem to set a Pffile object as a value for a Pfobject key in Objective-C. I'm trying to save NSData from an AVAudioPlayer in a PFfile.
If I do the folllowing:
NSData * audioData=[self.shoutInfoArray objectAtIndex:1];
PFFile * audiofile=[PFFile fileWithName:#"shoutData" data:audioData];
bool saved=[audiofile save]; //This bool is positive, so it does save!?
[shout fetchIfNeeded];
shout[#"audioData"]=audiofile; //BUGGY LINE
I get the following error:
Error: invalid type for key audioData, expected bytes, but got file
(Code: 111, Version: 1.2.20)
Couldn't find why?
Clear your database. I mean drop column audioData. It seams something wrong with types.
To Save a PFFile object as a part of PFObject:Also check file size should not be greater than 10MB.
PFFile * audiofile=[PFFile fileWithName:#"shoutData.aif" data:audioData];
[imageFile saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
//Use async call.
// It is compulsory to save the PFFile object first and then used it with PFObject
if(succeeded)
{
PFObject *shout = [PFObject objectWithClassName:#"UserData"];
shout[#"audioData"] = audiofile;
[shout saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if(error)
{
NSLog(#"error %#",error.localizedDescription);
}
else
{
if(succeeded)
{
NSLog(#"object save on parse");
}
}
}];
}
}];

How to convert a PFFile into a PFObject

I am using Parse. I have a PFFILE that I am retrieving using a Query. I need to save it, and i found that you normally use saveEventualy. But it doesn't support PFFile. So how can I turn the PFFile into a PFObject? Or else how save the image for offline? That's my code up to now:
-(void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self GetImage];
}
- (void)enteredForeground:(NSNotification*) not
{
[self GetImage];
}
-(void)GetImage
{
PFQuery *query = [PFQuery queryWithClassName:#"Image"];
[query getObjectInBackgroundWithId:#"4tmub1uxVd" block:^(PFObject *imageObject, NSError >*error)
{
if (imageObject) {
PFFile *imageFile = imageObject[#"image"];
[imageFile getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
if (data) {
UIImage *image = [UIImage imageWithData:data];
if (image) {
self.imageview.image = image;
}
} else {
NSLog(#"Error fetching image file: %#", error);
}
}];
} else {
NSLog(#"Error fetching object: %#", error);
}
}];
}
Parse has recently introduced a new method called local Data Store. It let's you store objects and files, update and retrieve them. Check out the documentation.
Blog Post
Documentation
That doesn't exactly answer your question, but it will achieve what you want it to!
You can't convert a PFFile to a PFObject, but you don't need to. The Image PFObject class you're fetching in the code above has a property, with key image, that represents a PFFile. If you modify this, you'd save the parent object, which would save the updated file alongside it.

How to load an image from Parse into a UIImageView (iOS)

I might be asking something really easy, but I can't manage to find a tutorial or example that would help me.
I have learned how to retrieve string data from Parse and now I am trying to retrieve an image thinking it would be easier.. but I can't figure it out.
I am trying to load 1 image (that I'll be changing every day) in the UIImageView, retrieving the image from my data browser in Parse.com.
Could somebody help please?
Here is what I've done:
- (void)viewDidLoad {
[super viewDidLoad];
[self performSelector:#selector(retrieveFromParse)];
}
- (void) retrieveFromParse {
PFQuery *retrieveImage = [PFQuery queryWithClassName:#"outfitDay"];
[retrieveImage findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
loadimageArray = [[NSArray alloc] initWithArray:objects];
}
}];
}
I am missing the part where you indicate the UIImageView to load that information.
Thanks in advance!!
You can set image in UIImageView with the help of this code.If you want to set image in imageview from with the help of url you can try this code.For this you have to download SDWebImages library
PFObject *objFollow1 = ["your array of PFObject" objectAtIndex:your index];
PFFile *image = [objFollow1 objectForKey:#"your key"];
NSLog(#"%#",teaserImage.url);
[your imageview setImageWithURL:[NSURL URLWithString:[teaserImage url]]];
And if you don't want to download image form url then you have to convert this PFFile in to NSData and then convert in to UIImage
You can set image using parse by below code...If you are storing image as PFFile....
PFFile *eventImage = [[loadimagesarray objectAtIndex:indexPath.row] objectForKey:#"ProfileImageFile"]; //ProfileImageFile is the name of key you stored the image file
if(eventImage != NULL)
{
[eventImage getDataInBackgroundWithBlock:^(NSData *imageData, NSError *error) {
UIImage *thumbnailImage = [UIImage imageWithData:imageData];
UIImageView *thumbnailImageView = [[UIImageView alloc] initWithImage:thumbnailImage];
cell.yourimageview.image = thumbnailImageView.image;
}];
}
If you want how to retrieve the details and save it in loadimagesarray use below code..
- (void)retrieveDetails
{
PFQuery *query = [PFQuery queryWithClassName:#"outfitDay"];
__block int totalNumberOfEntries = 0;
[query orderByDescending:#"createdAt"];
[query countObjectsInBackgroundWithBlock:^(int number1, NSError *error) {
if (!error) {
// The count request succeeded. Log the count
totalNumberOfEntries = number1;
if (totalNumberOfEntries > [loadimagesarray count])
{
NSLog(#"Retrieving data");
//query.skip=[NSNumber numberWithInt:2300];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
// The find succeeded.
NSLog(#"Successfully retrieved %d chats.", objects.count);
int j=[loadimagesarray count];
if([objects count]>j)
{
[loadimagesarray addObjectsFromArray:objects];
}
}
else
{
// Log details of the failure
NSLog(#"Error: %# %#", error, [error userInfo]);
}
}];
}
} else
{
// The request failed, we'll keep the chatData count?
number1 = [loadimagesarray count];
}
}];
}
Hope it works for you..
Loading an image from parse is easy with the PFImageView class. Below is an example of loading a PFFile from Parse, and showing it in a PFImageView, (or using a local placeholder image if remote file is not found):
PFImageView *profileImageView;
// User thumbnail
PFFile *imageFile = [self.author objectForKey:FIELDNAME_PROFILE_PROFILEPICTUREFILE];
if (imageFile) {
profileImageView.file = imageFile;
[profileImageView loadInBackground];
} else {
profileImageView.image = [UIImage imageNamed:#"AvatarPlaceholder.png"];
}
In your case, you would probably get the image from the array you've just retrieved...
For anyone who needs help! I found the answer to my question.
Found it in this example:
https://parse.com/questions/retrieve-images-from-parse-to-uiimageview
Hope it helps for someone else!!
And thanks to all who took the time to answer my question!

Resources