Delete item from the database of Parse.com (iOS App) - ios

I'm using Parse.com for my iOS application 8 ...
In parse database I created a new class called "Relationships", what I'm trying to do is prefix the user of my app to send a friend request to another user. I'm not using PFRelation because I need that friend request is not automatic, but accepted by the user.
In short, the user sends the request richeista of friendship and this remains within the class "Relationship" with the status "Waiting" until the subscriber does not accept the request.
Now I'm able to do everything I can:
User pointer to register the two (receiver and forwarder's friend request)
Insert the request status "pending"
My problem is that if my user does not want more 'send the request can not' delete ..
I tried using the ["name of PFObject" deleteInBackground] but I can not delete anything ...
Can you help me figure out how to delete the newly created data from the database to parse?
#pragma mark ADD FRIENDS
-(void)addFriendUserButtonPressed:(UITableViewCell *)customCell {
NSIndexPath *indexPath = [self.tableViewFindUser indexPathForCell:customCell];
PFObject *richiesta = [PFObject objectWithClassName:#"Relation"];
if (!isFiltered) {
PFUser *userFiltered = [self.userArray objectAtIndex:indexPath.row];
if (![self Is_InAttesa:userFiltered]) {
[richiesta setObject:userFiltered forKey:#"To_User"];
[richiesta setObject:[PFUser currentUser] forKey:#"From_User"];
[richiesta setObject:#"Pending" forKey:#"STATUS"];
[richiesta saveInBackground];
} else {
//[richiesta removeObject:[PFUser currentUser] forKey:#"From_User"];
//[richiesta setObject:userFiltered forKey:#"STATUS"];
//[richiesta saveInBackground];
}
}
else {
PFUser *userNotFiltered = [self.userFiltrati objectAtIndex:indexPath.row];
[richiesta setObject:userNotFiltered forKey:#"To_User"];
[richiesta setObject:[PFUser currentUser] forKey:#"From_User"];
[richiesta setObject:#"Pending" forKey:#"STATUS"];
[richiesta saveInBackground];
}
}
This is the Boolean method that I created to recognize (through a query) if users are present in the list of pending friend requests
-(BOOL)Is_InAttesa:(PFUser *)user_inattesa {
for (PFUser *userInAttesa in amiciInAttesaMutableArray) {
if ([[[userInAttesa objectForKey:#"To_User"]objectId] isEqualToString:user_inattesa.objectId]) {
return YES;
}
}
return NO;
}

Here is a method for deleting object from parse.
-(void)deleteButton {
//Query or retrieving data from dB which you want to delete.
PFQuery *query = [PFQuery queryWithClassName:#"YOUR_CLASS"];
//This string in below case takes name from textfield that user wants to delete. For your case you could modify it as per your need.
NSString *receiver_idStr =#"Id";
NSString *sender_idStr =#"Id";
// below two queries will work as like SELECT * FROM someTable WHERE senderId = 'id' AND receiverId = 'id'
[query whereKey:#"request_sender_id" containsString:sender_idStr];
[query whereKey:#"request_receiver_id" containsString:receiver_idStr];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) { //Query fired in background to search in parse for this object with condition provided.
if (!error) {
NSLog(#"Successfully retrieved: %#", objects);
//Now as you got object then you will type cast object from NSArray to PFObject and perform deleteInBackground method on them.
//Also update that UI part ,i.e., remove the request object from UI.
}
else {
NSLog(#"Error: %#", [error localizedDescription]);
}
}];
}
So this way to will be able to delete request object from parse. Also when user who has send the request cancel the request then also u search for that request object and do the same where else on user who receive request u could push notification to remove that request from it's UI.
In case user who receive request delete then it's simply find request object and delete, and update of UI for both sender and receiver.

-(void)addFriendUserButtonPressed:(UITableViewCell *)customCell {
NSIndexPath *indexPath = [self.tableViewFindUser indexPathForCell:customCell];
PFObject *richiesta = [PFObject objectWithClassName:NPFriendClass];
if (!isFiltered) {
PFUser *userFiltered = [self.userArray objectAtIndex:indexPath.row];
if (![self Is_InAttesa:userFiltered]) {
[richiesta setObject:userFiltered forKey:NPFriend_AUser];
[richiesta setObject:userFiltered.objectId forKey:#"OBJECT_USER_ID"];
[richiesta setObject:userFiltered.username forKey:#"Username"];
[richiesta setObject:[PFUser currentUser] forKey:NPFriend_DaUser];
[richiesta setObject:#"Richiesta In Attesa" forKey:NPFriendRequestStatus];
[richiesta saveInBackground];
} else {
PFQuery *query = [PFQuery queryWithClassName:NPFriendClass];
[query whereKey:NPFriend_DaUser equalTo:[PFUser currentUser]];
[query whereKey:NPFriendRequestStatus equalTo:#"Richiesta In Attesa"];
[query whereKey:#"OBJECT_USER_ID" equalTo:userFiltered.objectId];
[query includeKey:NPFriend_AUser];
[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if(!error) {
for (PFObject *object in objects) {
NSLog(#"Successfully retrieved: %#", object);
[object deleteInBackground];
}
}
else {
NSLog(#"Error: %#", [error localizedDescription]);
}
}];
}
}
else {
PFUser *userNotFiltered = [self.userFiltrati objectAtIndex:indexPath.row];
[richiesta setObject:userNotFiltered forKey:NPFriend_AUser];
[richiesta setObject:[PFUser currentUser] forKey:NPFriend_DaUser];
[richiesta setObject:#"Richiesta In Attesa" forKey:NPFriendRequestStatus];
[richiesta saveInBackground];
}
}
Hello Walle thanks again for your help you have been very kind and helpful ...
I fixed it this way and it seems to work ...
The only problem that remains is that it does not update the data immediately so the user can not figure out if you sent the request or not. The tableview is updated only if it does refresh the Tableview or change viewcontroller ..
I tried to redo do the query again as soon as the user sends a friend request but overlapping data and slows down the app ... How can I get the data refresh every minute without calling the query?
The idea of the button selected or not starch could be good? I'm trying but maybe something wrong because I can not get it to work

Related

Parse- [query findObjectsInBackgroundWithBlock:^.)]; Block Doesn't execute w/ Action Extension

I'm trying to develop and Action Extension for iOS9.1 that is supposed to query Parse for some data.
I've added, enabled and tested Parse in the extension and I'm successful at creating test objects and checking for current user.
I can not get the code inside Parse's query method
[query findObjectsInBackgroundWithBlock:^ to execute. LLDB just keeps skipping it so I'm really at a loss.
This code executes perfectly within the container app so I'm a bit confused.
- (void)viewDidLoad
{
[super viewDidLoad];
[Parse enableLocalDatastore];
[Parse enableDataSharingWithApplicationGroupIdentifier:#"group.com.app.slinky"
containingApplication:#"com.app.Slinky"];
[Parse setApplicationId:#"xxxxx"
clientKey:#"xxxxx"];
for (NSExtensionItem *item in self.extensionContext.inputItems) {
for (NSItemProvider *itemProvider in item.attachments) {
if ([itemProvider hasItemConformingToTypeIdentifier:(NSString *)kUTTypePropertyList]) {
[itemProvider loadItemForTypeIdentifier:(NSString *)kUTTypePropertyList options:nil completionHandler:^(NSDictionary *jsDict, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
NSDictionary *jsPreprocessingResults = jsDict[NSExtensionJavaScriptPreprocessingResultsKey];
NSString *pageTitle = jsPreprocessingResults[#"title"];
NSString *pageURL = jsPreprocessingResults[#"URL"];
if ([pageURL length] > 0) {
self.siteURL.text = pageURL;
self.URLstring = pageURL;
}
if ([pageTitle length] > 0) {
self.siteTitle.text = pageTitle;
}
});
}];
break;
}
}
}
[self queryParse];
}
-(void)queryParse{
PFQuery *query = [self.friendsRelation query];
[query orderByAscending:#"username"];
**[query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
if (error) {
NSLog(#"%# %#", error, [error userInfo]);
} else {
self.friends = objects;
[self.tableView reloadData];
}
}];**
}
There are some limit to fetch Objects from Parse. Read Here
One has a limit of obtaining 100 objects, but anything from 1 to 1000 has a valid limit.
You have to set the limit again for the query for next objects and skip the properties of PFQuery.
You will have to query again and again until you reach the total count.
For Example - If you have 3000 objects to be fetched, then you have to query 3 times with a count of say 1000.
OR
Call [self queryParse]; inside dispatch_async(dispatch_get_main_queue(), ^{ }); block.
Hope this might workout.
This was just a result of a 12 hour refractoring marathon :-(
When I moved the queryParse call into its own method. I lost the definition of
self.friendsRelation = [[PFUser currentUser] objectForKey:#"friendsRelation"];
essentially sending a bad query... I don't know why it isn't return an error but regardless I can check that off now.
Thank you all for you help!

PFRelation won't save on Parse.com

I am having trouble saving a PFRelation I have this code:
//set up the query
PFQuery *query = [PFQuery queryWithClassName:#"messageBank"];
[query whereKey:#"username" equalTo:name];
__weak User *weakSelf = self;
[query getFirstObjectInBackgroundWithBlock:^(PFObject *object, NSError *error) {
if(error) {
NSLog(#"No such user");
handler(NO, error,NO,NO);
}
else{
[weakSelf.friendsRelation addObject:object];
[weakSelf.friends addObject:object];
//save in the background
[weakSelf.messageBank saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if(error) {
NSLog(#"Save error");
}
else {
NSLog(#"no error");
}
}];
handler(YES,nil,NO,NO); //no errors
//so the friend is added to the friends array, all we need to do is reload the table data don't need to init the array again, the relation is also added to the relation item so don't need to init that again
}
}];//end block
My code finds the messageBank object fine but it won't save it to the PFRelation friends. It doesn't even attempt to call [weakSelf.messageBank saveInBackgroundWithBlock.... weakSelf.messageBank is the local PFObject and weakSelf.friends is it's PFRelation. Anyone have any ideas what could be going wrong here? If I have a PFRelation in class A is it okay to have pointers in that relation to other objects in class A? Does it need to be in a different class? Any help would be much appreciated!!!
Here's a cleaned up version of the code that fetches an object and adds to its relation, and saves it...
PFQuery *query = [PFQuery queryWithClassName:#"messageBank"]; // by convention class names should be capital MessageBank, but using yours
[query whereKey:#"username" equalTo:name]; // better form is self.name assuming it is an attribute of self
[query getFirstObjectInBackgroundWithBlock:^(PFObject *object, NSError *error) {
if (!error) {
// see note below about weakSelf
// assume self is a PFObject subclass with two relations
// (and generated setters) called friendsRelation and friends
[self.friendsRelation addObject:object];
[self.friends addObject:object];
// notice we save self here. that's who changed in the two preceding lines
[self saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if(!error) {
// success
} else {
// handle error
}
}];
} else {
// handle error
}
}];
Please notice that there's no need to declare a __weak copy of the self pointer (though, there's no harm in it). That idiom is used to avoid a retain cycle between self and the block's owner. You need it only when self is the blocks owner (directly or indirectly). This isn't the case with parse's completion blocks.

How do I delete a row from a Parse object?

I have a class on Parse.com called "Hospital", which has a few rows on it. I want to query all the rows in this object, and then selectively delete some of them.
I figure I need to cycle through the object, gathering the objectIDs, and then look at the row associated with each ID to figure out which ones should be deleted. I can't find how to do this anywhere. I've tried this:
PFQuery *query = [PFQuery queryWithClassName:#"Hospital"];
But this returns an object with 0 objects inside it, when there is definitely a row in the Parse.com database.
Once I get this part working, and get objectIDs, it seems I can delete a row with the following:
PFObject *testObject = [PFObject objectWithoutDataWithClassName:#"Hospital" objectId:#"NMZ8gLj3RE"];
[testObject deleteInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (succeeded){
NSLog(#"BOOOOOM"); // this is my function to refresh the data
} else {
NSLog(#"DELETE ERRIR");
}
}];
PFQuery *query = [PFQuery queryWithClassName:#"Hospital"];
[query findObjectsInBackgroundWithBlock:^(NSArray *hospitals, NSError *error) {
if (!error)
{
for (PFObject *hospital in hospitals)
{
if ([hospital.objectId isEqualToString:#"NMZ8gLj3RE"])
{
[hospital deleteInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
if (succeeded){
NSLog(#"BOOOOOM"); // this is my function to refresh the data
} else {
NSLog(#"DELETE ERRIR");
}
}];
}
}
}
else
{
NSLog(#"%#",error);
}
}];

Retrieving Profile Picture iOS Parse.com

I'm having an issue retrieving the a profile picture from a PFFile column in the Parse User class. I read in the docs that you need to use the PFUser object to query the User class. Right now no image is showing up. Here is my code:
PFUser *user = [PFQuery getUserObjectWithId:[PFUser currentUser].objectId];
[user fetchIfNeededInBackgroundWithBlock:^(PFObject *object, NSError *error) {
_profileImage.file = [object objectForKey:#"profilePicture"];
}];
(1) The current user's PFUser object is in fact [PFUser currentUser] so all that code in your first line could be replaced with:
PFUser *user = [PFUser currentUser];
(2) Everything else looks OK, but if you're using a PFImageView, your [profileImage loadInBackground]; call should also be within the fetchIfNeededInBackgroundWithBlock: async block.

Updating Saved Data in Parse iOS

I use this code to update my data on data browser on parse.
PFQuery *query = [PFQuery queryWithClassName:#"UserInformation"];
[query getObjectInBackgroundWithId:#"dIwnk9tbr0" block:^(PFObject *gameScore, NSError *error)
{
gameScore[#"email_address"] = #"testkolang#y.com";
[gameScore saveInBackground];
}];
But I have this kind of error. And the data on parse is not changed.
2014-03-12 18:08:06.036 AndroidiOsPushTest[3725:1803] Error: object not found for update (Code: 101, Version: 1.2.18)
PFQuery *query = [PFUser query];
[query getObjectInBackgroundWithId:objectID block:^(PFObject *UserInfo, NSError *error) {
if (!error) {
[UserInfo setObject:self.userName.text forKey:#"username"];
[UserInfo setObject:#"US" forKey:#"country"];
[UserInfo saveInBackground];
}
else {
// Did not find any UserStats for the current user
NSLog(#"Error: %#", error);
}
}];
Your issue looks like the one in : I can not update a record in Parse; Error: "object not found for update (Code: 101, Version: 1.2.16)"
Error code 101 in Parse means :
101: Object doesn't exist, or has an incorrect password.
First, you should check if your object exists and if the error is not null.
Then, if these steps are successful, you should check for the ACL of the object : if you don't have permissions to edit it, you will be unable to save it and get the error 101.
It relate to ACL, please check your dashboard for the data column "ACL"
The write should lock on specific user ID. you need change it from your dashboard to update its permission to
{"*":{"write":true,"read":true}}
You can check more detail on my reply in this
From Parse.com (Hector Ramos)
PFQuery *query = [PFQuery queryWithClassName:#"UserStats"];
[query whereKey:#"user" equalTo:[PFUser currentUser]];
[query getFirstObjectInBackgroundWithBlock:^(PFObject * userStats, NSError *error) {
if (!error) {
// Found UserStats
[userStats setObject:newScore forKey:#"latestScore"];
// Save
[userStats saveInBackground];
} else {
// Did not find any UserStats for the current user
NSLog(#"Error: %#", error);
}
}];

Resources