【问题标题】:Delete PFUser with Cloud Code Parse.com iOS使用 Cloud Code Parse.com iOS 删除 PFUser
【发布时间】:2015-05-11 18:14:20
【问题描述】:

我成功添加了 Cloud CodeParse.com 的朋友。

现在我想在 didSelectRowAtIndexPath

中删除与 Cloud Code 的好友关系

我的错误是“attempt to insert nil object from objects[0]'

但是不知道需要配置什么参数,我找到了ma​​in.js的云代码:

Parse.Cloud.define("removeFriend", function(request, response) 
{
    // here's how to get the client's user making the request
    var user = request.user;

    // consider checking that user && request.params.friend are valid
    // if not, return response.error("missing user or friend id")

    getUser(request.params.friend).then(function(friend) {
        // your code prematurely called response.success() here, thereby canceling any further steps
        friend.relation("friendsRelation").remove(user);
        // return the promise returned by save() so we can chain the promises
        return friend.save();
    }).then(function(result) {
        // only now that the save is finished, we can claim victory
        response.success(result);
    }, function (error) {
        response.error(result);
    });
});

// EDIT - the OP once referred to a getUser function that we assume to be something like this:
// return a promise to get a user with userId
function getUser(userId) {
    var userQuery = new Parse.Query(Parse.User);
    return userQuery.get(userId);
}

这是我的代码 EditFriends.m :

    - (void)viewDidLoad
    {
        [super viewDidLoad];
        PFQuery *query = [PFUser query];
        [query orderByAscending:@"name"];
        [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
            if (error) {
                NSLog(@"Error: %@ %@", error, [error userInfo]);
            }
            else {
                self.allUsers = objects;
                [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:NO];
            }
        }];

        self.currentUser = [PFUser currentUser];
        [self loadFriends];
    }

-(void) loadFriends{
    self.friendsRelation = [[PFUser currentUser] objectForKey:@"friends"];
    PFQuery *query = [self.friendsRelation query];
    [query orderByAscending:@"username"];
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error)
     {
         if (error) {
             NSLog(@"Error %@ %@", error, [error userInfo]);
         }
         else {
             self.friends = objects;

             [self.tableView reloadData];
         }
     }];
}


    - (BOOL)isFriend:(PFUser *)user {
        for(PFUser *friend in self.friends) {
            if ([friend.objectId isEqualToString:user.objectId]) {
                return YES;
            }
        }

        return NO;
    }

CellForRowAtIndexPath :

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];

    PFUser *user = [self.allUsers objectAtIndex:indexPath.row];

    NSString *name = [[self.allUsers objectAtIndex:indexPath.row] valueForKey:@"username"];
    cell.textLabel.text = name;

    if ([self isFriend:user]) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;

    } else {

        cell.accessoryType = UITableViewCellAccessoryNone;
    }

    return cell;
}

didSelectRowAtIndexPath :

PFUser *selected = [self.allUsers objectAtIndex:indexPath.row];
    if ([self isFriend:selected]) {
        NSLog(@"déjà amis");
//        PFObject *friendRequest = [self.friendRequests objectAtIndex:indexPath.row];
        [PFCloud callFunctionInBackground:@"removeFriend" withParameters:@{@"friendRequest" : selected.objectId} block:^(id object, NSError *error) {

            if (!error) {
                //add the fromuser to the currentUsers friends

                //save the current user
                [self.currentUser saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {

                    if (succeeded) {



                    } else {

                    }

                }];

            }
            else {

            }


        }];

    }
else{
    PFUser *selectedUser = [self.allUsers objectAtIndex:indexPath.row];
    //request them
    PFObject *friendRequest = [PFObject objectWithClassName:@"FriendRequest"];
    friendRequest[@"from"] = self.currentUser;
    friendRequest[@"fromUsername"] = [[PFUser currentUser] objectForKey:@"username"];
    //selected user is the user at the cell that was selected
    friendRequest[@"to"] = selectedUser;
    // set the initial status to pending
    friendRequest[@"status"] = @"pending";
    [friendRequest saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {

        if (succeeded) {


            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Yay" message:@"Friend request sent" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];



        } else {

            // error occurred
        }
    }];
}

【问题讨论】:

    标签: ios objective-c parse-platform parse-cloud-code pfuser


    【解决方案1】:

    iOS 代码看起来没问题,只需要确保它发送正确的用户 objectId。

    云代码很接近,但必须改进一点:

    Parse.Cloud.define("removeFriend", function(request, response) 
    {
        // here's how to get the client's user making the request
        var user = request.user;
    
        // consider checking that user && request.params.friend are valid
        // if not, return response.error("missing user or friend id")
    
        getUser(request.params.friendRequest).then(function(friend) {
            // your code prematurely called response.success() here, thereby canceling any further steps
            console.log("relation is:" + JSON.stringify(friend.relation("friends")));
            friend.relation("friends").remove(user);
            // return the promise returned by save() so we can chain the promises
            return friend.save();
        }).then(function(friend) {
            // friendship goes both ways, so remove the friend from user's friends
            user.relation("friends").remove(friend);
            return user.save();
        }).then(function(result) {
            // only now that the save is finished, we can claim victory
            console.log("relation is:" + JSON.stringify(result.relation("friends")));
            response.success(result);
        }, function (error) {
            response.error(error);
        });
    });
    
    // EDIT - the OP once referred to a getUser function that we assume to be something like this:
    // return a promise to get a user with userId
    function getUser(userId) {
        var userQuery = new Parse.Query(Parse.User);
        return userQuery.get(userId);
    }
    

    编辑 - 调用:

    PFUser *selected = [self.allUsers objectAtIndex:indexPath.row];
    if ([self isFriend:selected]) {
        NSLog(@"déjà amis");
        [PFCloud callFunctionInBackground:@"removeFriend" withParameters:@{@"friendRequest" : selected.objectId} block:^(id object, NSError *error) {
        // etc.
    

    【讨论】:

    • 嘿,谢谢你的回复!我想我没有发送正确的用户objectId,因为我的应用程序再次崩溃:[__NSPlaceholderDictionary initWithObjects:forKeys:count:]:尝试从对象[0]'中插入零对象...所以有些对象是零,我不'不知道我做错了什么,我没有更改我的 iOS 代码。
    • 我成功在didSelectRowAtIndexPath中获取了用户objectId,代码如下:PFUser *user = [self.allUsers objectAtIndex:indexPath.row]; NSString *objectId = [用户 objectId];但接下来我要做什么?非常感谢!
    • 这是因为friendRequest为nil,但我不知道如何修复它,我需要什么参数......我用Parse的截图更新了我的帖子
    • 云代码需要一个当前用户和另一个用户的 id,该用户在其 FriendsRelation 中拥有当前用户。 When a user is selected where isFriend == YES, I think you should skip all of that code and just call the cloud with the selected user's object id.
    • 好的,我理解了这个过程,我已经在 didSelect 中编辑了我的代码......所以,我在 viewDidLoad 中有当前用户:self.currentUser,所选用户 id 在 didSelect 和 selected.objectId 中.我试图启动我的应用程序,它并没有崩溃,但它说:[错误]:ReferenceError:getUser 未在 main.js:81:5 定义(代码:141,版本:1.7.2)跨度>
    猜你喜欢
    • 2014-09-21
    • 1970-01-01
    • 1970-01-01
    • 2016-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多