I want to download the image in a UIImageView user from Parse. In the User section, I created the UserImage section, but I can not download it into UIImageView, what should I do? You give me a hand? Help me please.
I've used this code:
PFUser* currentUser = [PFUser currentUser];
if (currentUser) {
PFQuery* queryPhoto = [PFQuery queryWithClassName:#"UserImage"];
[queryPhoto findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
// Verify if there are no errors
if (!error) {
// Retrieve Usename
User.text = [NSString stringWithFormat:#"%#",[[PFUser currentUser]valueForKey:#"username"]] ;
// Retrieve Photo
PFUser *currentuser = [PFUser currentUser];
PFFile *file = [currentuser objectForKey:#"UserImage"];
[file getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
if (!error) {
UIImage *image = [UIImage imageWithData:data];
// image can now be set on a UIImageView
self.UserImages.image = image;
}
}];
}
else {
NSString *errorString = [[error userInfo] objectForKey:#"error"];
UIAlertView *errorAlertView = [[UIAlertView alloc] initWithTitle:#"Error" message:errorString delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[errorAlertView show];
}
} ];
}
Parse.com has the PFImageView specifically to make this task eaiser.
Try this:
PFUser* currentUser = [PFUser currentUser];
if (currentUser) {
PFQuery* queryPhoto = [PFQuery queryWithClassName:#"UserImage"];
[queryPhoto findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
// Verify if there are no errors
if (!error) {
// Retrieve Usename
User.text = [NSString stringWithFormat:#"%#",[[PFUser currentUser]valueForKey:#"username"]] ;
// Retrieve Photo & Load
PFFile *file = [currentUser objectForKey:#"UserImage"];
PFImageView *imageView = [[PFImageView alloc] init];
self.UserImages.image = imageView; //Assuming here that you set self.UserImages.image as a PFImageView
self.UserImages.image.file = file;
[self.UserImages.image loadInBackground];
}
else {
NSString *errorString = [[error userInfo] objectForKey:#"error"];
UIAlertView *errorAlertView = [[UIAlertView alloc] initWithTitle:#"Error" message:errorString delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil, nil];
[errorAlertView show];
}
}];
}
Related
I need help posting a picture onto a tableview after i posted to parse. I am using parse and objective-c. I got to where you can post a picture and I can see it on parse, but how can I see the picture on like a timeline in my app or a table view?
Here is my code for posting to parse,
- (IBAction)uploadButton:(id)sender{
NSData* data = UIImageJPEGRepresentation(_imageView.image, 100);
PFFile *imageFile = [PFFile fileWithName:#"Image.jpg" data:data];
// Save the image to Parse
[imageFile saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (!error) {
// The image has now been uploaded to Parse. Associate it with a new object
PFObject* newPhotoObject = [PFObject objectWithClassName:#"PhotoObject"];
[newPhotoObject setObject:imageFile forKey:#"image"];
[newPhotoObject saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (!error) {
NSLog(#"Saved");
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Success" message:#"Your picture has been successfully uploaded." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
else{
// Error
NSLog(#"Error: %# %#", error, [error userInfo]);
}
}];
}
}];
}
What else do I need to put in order to see what I posted on my main tableview page?
I labeled the view controllers "posting page" and the "main page". The "main page" is where I want all the pictures I post to parse to end up, with a comment section for the picture.
i have done like this , may be useful to you. take a look
-(IBAction)btnUpDateImageClicked:(id)sender
{
if (UserSelectedImage)
{
HUDSHOWWITHTEXT(#"Updating profile");
PFQuery *query = [PFQuery queryWithClassName:User_Info];
NSLog(#"->%#",[PFUser currentUser].username);
[query whereKey:UserName equalTo:[PFUser currentUser].username];
[query getFirstObjectInBackgroundWithBlock:^(PFObject * user , NSError *error) {
if (!error) {
// Found User and modify it
PFFile *imageFile1,*imageFilePlaceHolder;
NSData *imageData1,*imageDataPlaceHolder;
// PFFile *fileDeleted = [[PFFile alloc] init];
if (UserSelectedImage) {
//User image
imageData1 = UIImageJPEGRepresentation(UserSelectedImage, 1.0);
imageFile1 = [PFFile fileWithName:#"img.png" data:imageData1];
[user setObject:imageFile1 forKey:#"user_image"];
//PlaceHolder
UIImage *imagPlaceholder = UserSelectedImage;
imagPlaceholder = [APP_DELEGATE SyncPlaceHolderImage:imagPlaceholder];
imageDataPlaceHolder = UIImageJPEGRepresentation(imagPlaceholder, 1.0);
imageFilePlaceHolder = [PFFile fileWithName:#"img.png" data:imageDataPlaceHolder];
[user setObject:imageFilePlaceHolder forKey:#"placeholder_image"];
}
else {
user[#"user_image1"] = [NSNull null];
user[#"placeholder_image"] = [NSNull null];
}
// Save
[user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (succeeded) {
HUDHIDE;
if (UserSelectedImage) {
APP_DELEGATE.user.pfImageOne = imageFile1;
APP_DELEGATE.user.pfImagePlaceHolder= imageFilePlaceHolder;
}
else {
APP_DELEGATE.user.pfImageOne = nil;
APP_DELEGATE.user.pfImagePlaceHolder=nil;
}
ShowAlert(#"Saved SUccesfully");
}
else
{
HUDHIDE;
ShowAlert(#"Problem updating profile-%#");
}
}];
} else {
// Did not find any UserStats for the current user
NSLog(#"Error: %#", error);
HUDHIDE;
ShowAlert(#"Problem updating profile")
}
}];
}
else
{
ShowAlert(#"please select Image");
}
}
I have a problem.
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
UIImage* image = [info objectForKey:UIImagePickerControllerOriginalImage];
UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil);
[self dismissViewControllerAnimated:YES completion:^{
if (image == nil){
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Try again !" message:#"Please try again." delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
[self presentViewController:self.imagePicker animated:NO completion:nil];
}else{
NSData *fileData;
NSString *fileName;
NSString *fileType;
fileData = UIImagePNGRepresentation(image);
fileName = #"profilePic.png";
fileType = #"Image";
PFFile *file = [PFFile fileWithName:fileName data:fileData];
[file saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"An error occurred!"
message:[NSString stringWithFormat:#"Please try sending your message again. %#",error.userInfo]
delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}else{
[[PFUser currentUser]setObject:file forKey:#"profilePic"];
[[PFUser currentUser] saveInBackgroundWithBlock:^(BOOL succeed, NSError* error){
if (!error) {
NSLog(#"New profile pic loaded.");
[self.activity stopAnimating];
[self.reloadPicBtn setHidden:NO];
}else{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Try again !" message:#"Please try again. Failed to load your new profile pic :(" delegate:self cancelButtonTitle:#"OK" otherButtonTitles: nil];
[alert show];
}
}];
}
}];
}
}];
}
Well, reloadPicBtn is shown, but if I call a function which reloads a picture, It fails. And when I try to understand WTF is going on using NSLog it logs out a string. So code has been executed. But there is no result on screen. The function is the same which is called in viewDidLoad. But it works when it is called from viewDidLoad. And when it is called again there is no result.
That reload function:
- (void) loadProfilePic{
PFQuery* query = [PFUser query];
[query getObjectInBackgroundWithId:[PFUser currentUser].objectId block:^(PFObject* object, NSError* error){
if(!error){
PFFile* imageFile = object[#"profilePic"];
[imageFile getDataInBackgroundWithBlock:^(NSData* data, NSError* error){
if (!error) {
self.activity.hidden = NO;
[self.activity startAnimating];
self.profilePic.image = [UIImage imageWithData:data];
NSLog(#"Profile pic shown");
}
else{
NSLog(#"Error 2: %#",error);
}
}];
}else{
self.profilePic.image = [UIImage imageNamed:#"profile#2.png"];
NSLog(#"Fail 1 : %#",error);
}
}];
}
Please help me.
It prints out profile pic shown. But it doesn't even use network to download an image.
I m using Parse SDK. I want to get the data from the Parse API table,and want to set the filters as Username and password. How can I achieve this. Below given is the sample code which was done with the help of NSURLSession and wants it to be converted to a code using Parse SDK classes.
-(void)validateLoginWithUsername:(NSString *)usernam withPassword:(NSString *)pasword
{
NSString *urlString = [NSString stringWithFormat:#baseURL#"/1/login?username=%#&password=%#",usernam,pasword];
NSURL *url = [NSURL URLWithString:urlString];
NSURLSessionConfiguration *sessionConfiguration = [NSURLSessionConfiguration defaultSessionConfiguration];
sessionConfiguration.HTTPAdditionalHeaders = #{ #AppId : #id1,
#APIKey : #key1 };
self.session = [NSURLSession sharedSession];
self.session = [NSURLSession sessionWithConfiguration:sessionConfiguration];
NSURLSessionDataTask * dataTask = [self.session dataTaskWithURL:url
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error)
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if (httpResponse.statusCode == 200)
{
NSDictionary *dataToBeTransferedBack = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
ATTDataLibrary *instance = [ATTDataLibrary getInstanceOfDataLibrary];
[instance manupulateUserData:dataToBeTransferedBack];
[singletonInstance getTheSubjectsData];
}
else
{
dispatch_sync(dispatch_get_main_queue(), ^{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Invalid Login" message:#"Please Check the username and password entered" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil, nil];
[alert show];
});
}
Please check Parse Integration here to add parse to your existing project.
Please try below code:
// If you are using Custom Table then
PFQuery *query = [PFQuery queryWithClassName:#"TableName"];
[query whereKey:#"username" equalTo:#"pass your username here"];
[query whereKey:#"password" equalTo:#"pass your password here"];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error){
if(!error){
if(objects.count>0)
// Found User
}
}];
Or You are using USER table then try below code
[PFUser logInWithUsernameInBackground:username password:password
block:^(PFUser *user, NSError *error) {
if (user) {
// Found User
} else {
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Login Error" message:#"Credentials provided were incorrect. Please try again." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
}
}];
Assuming that you have already integrate Parse SDK on your code.
Using following method.
-(void)validateLoginWithUsername:(NSString *)usernam withPassword:(NSString *)pasword
{
[PFUser logInWithUsernameInBackground:usernam password:pasword
block:^(PFUser *user, NSError *error) {
if (user) {
// Do stuff after successful login.
} else {
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Invalid Login" message:#"Please Check the username and password entered" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil, nil];
[alert show];
}
}];
}
You can retrieve the records using parse API using below code...
You can apply filters using where class of PFQuery
PFQuery *query = [PFQuery queryWithClassName:#"UserDetails"];
__block int totalNumberOfEntries = 0;
[query orderByDescending:#"createdAt"];
[query whereKey:#"UserName" containsString:#"anand"];
[query whereKey:#"Password" containsString:#"1234"];
[query countObjectsInBackgroundWithBlock:^(int number1, NSError *error)
{
if (!error)
{
NSLog(#"------- number-- %d",number1);
NSLog(#"------- number-- %d",[profileArray count]);
if (totalNumberOfEntries > [profileArray count])
{
NSLog(#"Retrieving data");
//query.skip=[NSNumber numberWithInt:2300];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (!error) {
// The find succeeded.
NSLog(#"Successfully retrieved %d records.", objects.count);
int j=[profileArray count];
if([objects count]>j)
{
[profileArray addObjectsFromArray:objects];
NSLog(#"array count is %d",[profileArray count]);
NSLog(#"array is %#",profileArray);
}
}
else
{
// Log details of the failure
NSLog(#"Error: %# %#", error, [error userInfo]);
}
}];
}
} else
{
// The request failed, we'll keep the Data count?
number1 = [profileArray count];
}
}];
Hope it is useful to you...!
I have an application where I have two parse tables - "User" and "Topics". Now what I want is that if any user signs up, then I want to create another parse table which will store some info related to that user and the topic say topic progress. Here's my code -
- (IBAction)signUpFunction {
[self.view endEditing:YES];
NSString *fullName = self.nameTextField.text;
NSString *username = self.usernameTextField.text;
NSString *password = self.passwordTextField.text;
NSString *email = self.emailTextField.text;
if ([username length] == 0 || [password length] == 0 || [email length] == 0 || [fullName length] == 0)
{
[[[UIAlertView alloc] initWithTitle:#"Missing Information"
message:#"Make sure you fill out all of the information!"
delegate:nil
cancelButtonTitle:#"ok"
otherButtonTitles:nil] show];
}
else {
PFUser *newUser = [PFUser user];
newUser.username = username;
newUser.password = password;
newUser.email = email;
newUser[#"fullName"] = fullName;
[newUser signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (error) {
[[[UIAlertView alloc] initWithTitle:#"Error!"message:[error.userInfo objectForKey:#"error"] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil] show ];
}
else
{
PFQuery *topicsQuery = [PFQuery queryWithClassName:#"Topic"];
[topicsQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (error) {
NSLog(#"Error: %# %#", error, [error userInfo]);
}
else {
for (unsigned int i = 0; i < objects.count; i++) {
PFObject *object = objects[i];
PFObject *topicProgressForUser = [PFObject objectWithClassName:#"QuizProgress"];
[topicProgressForUser setObject:[PFUser currentUser] forKey:#"user"];
[topicProgressForUser setObject:object forKey:#"topic"];
if ([object[#"fullAccess"] isEqualToString:#"Yes"]) {
[topicProgressForUser setObject:#"Free" forKey:#"purchased"];
} else {
[topicProgressForUser setObject:#"No" forKey:#"purchased"];
}
[topicProgressForUser setObject:0 forKey:#"questionsSolved"];
[topicProgressForUser setObject:0 forKey:#"attempts"];
[topicProgressForUser setObject:0 forKey:#"resultInPercentage"];
[topicProgressForUser setObject:#"Basic" forKey:#"achievement"];
[topicProgressForUser setObject:NO forKey:#"generateCertificate"];
[topicProgressForUser saveEventually];
}
}
}]; // topic block
}
}]; // signup block
}
}
I don't think I am using the right standard of saving data to parse cloud by saving each pfobject individually. What if the internet connection is lost in the middle of saving objects ? Can anyone help me in using the correct and fast approach of saving multiple pfobject data to new table in parse cloud.
In your case, I would take a look at the class methods saveAll, saveAllInBackground, etc.
I took your code and modified it how I think makes the most sense in this case. Let me know if it works:
- (IBAction)signUpFunction {
[self.view endEditing:YES];
NSString *fullName = self.nameTextField.text;
NSString *username = self.usernameTextField.text;
NSString *password = self.passwordTextField.text;
NSString *email = self.emailTextField.text;
if ([username length] == 0 || [password length] == 0 || [email length] == 0 || [fullName length] == 0) {
[[[UIAlertView alloc] initWithTitle:#"Missing Information"
message:#"Make sure you fill out all of the information!"
delegate:nil
cancelButtonTitle:#"ok"
otherButtonTitles:nil] show];
} else {
PFUser *newUser = [PFUser user];
newUser.username = username;
newUser.password = password;
newUser.email = email;
newUser[#"fullName"] = fullName;
[newUser signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (error) {
[[[UIAlertView alloc] initWithTitle:#"Error!"message:[error.userInfo objectForKey:#"error"] delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil] show ];
} else {
PFQuery *topicsQuery = [PFQuery queryWithClassName:#"Topic"];
[topicsQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (error != nil) {
NSLog(#"Error: %# %#", error, [error userInfo]);
} else {
NSMutableArray *topics = [NSMutableArray array];
for (unsigned int i = 0; i < objects.count; i++) {
PFObject *object = objects[i];
PFObject *topicProgressForUser = [PFObject objectWithClassName:#"QuizProgress"];
[topics addObject:topicProgressForUser];
topicProgressForUser[#"user"] = [PFUser currentUser];
topicProgressForUser[#"topic"] = object;
topicProgressForUser[#"questionSolved"] = #(NO);
topicProgressForUser[#"attempts"] = #(0);
topicProgressForUser[#"resultInPercentage"] = #(0);
topicProgressForUser[#"achievement"] = #"Basic";
topicProgressForUser[#"generateCertificate"] = #(NO);
if ([object[#"fullAccess"] isEqualToString:#"Yes"]) {
topicProgressForUser[#"purchased"] = #"Free";
} else {
topicProgressForUser[#"purchased"] = #"No";
}
}
[PFObject saveAllInBackground:objects block:^(BOOL succeeded, NSError *error) {
if (error != nil) {
// Do something here to handle the error
} else {
//
}
}
]; // saveAllInBackground
}
}]; // topic block
}
}]; // signup block
}
}
Change the below line of code:
[topicProgressForUser saveEventually];
to
[topicProgressForUser saveInBackground];
Hope this helps..
I have some issues with user photos (profile pictures). For every time a single user update his profile picture, it also updates the rest of the users with the same image. How do I change it so it doesn't change everywhere? I am using parse.com
I'm using following codes.
Uploading the photo:
- (void)uploadProfilePhoto {
NSData *imageData;
NSString *imageName;
NSString *imageType;
//Shrink it
//Upload profile photo
(self.image != nil); {
UIImage *resizeImage = [self resizeImage:self.image toWidth:320.0f andHeight:320.0f];
imageData = UIImagePNGRepresentation(resizeImage);
imageName = #"profileimage.png";
imageType = #"image";
}
PFFile *image = [PFFile fileWithName:imageName data:imageData];
[image saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Something went wrong!" message:#"Please try again." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
else {
PFObject *UserPhotos = [PFObject objectWithClassName:#"UserPhoto"];
[UserPhotos setObject:image forKey:#"image"];
[UserPhotos setObject:imageType forKey:#"imageType"];
[UserPhotos setObject:[PFUser currentUser] forKey:#"user"];
[UserPhotos setObject:[[PFUser currentUser] objectId] forKey:#"uploaderId"];
[UserPhotos setObject:[[PFUser currentUser] username] forKey:#"uploaderUsername"];
[UserPhotos saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Something went wrong!" message:#"Please try uploading your photo again." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
else {
//Everything was successfull!
}
}];
}
}];
}
When I retrieve the photo:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
PFQuery *query = [PFQuery queryWithClassName:#"UserPhoto"];
[query includeKey:#"user"];
[query orderByDescending:#"createdAt"];
[query getFirstObjectInBackgroundWithBlock:^(PFObject *object, NSError *error) {
if (!object) {
return NSLog(#"%#", error);
}
PFFile *imageFile = object[#"image"];
[imageFile getDataInBackgroundWithBlock:^(NSData *data, NSError *error) {
if (!data) {
return NSLog(#"%#", error);
}
// Do something with the image
self.profileImage.image = [UIImage imageWithData:data];
}];
}];
[self.navigationController.navigationBar setHidden:YES];
}
Thanks!