Search code examples
iosswiftparse-platformparse-cloud-code

Calling function in Parse Cloud Code


I am working with cloud code for the first time and am trying to call the following function:

       let friendRequest: PFObject = self.friendRequestsToCurrentUser[sender.tag] as PFObject
      let fromUser: PFUser = friendRequest[FriendRequestKeyFrom] as PFUser
      //call the cloud code function that adds the current user to the user who sent the request and pass in the friendRequest id as a parameter
        PFCloud.callFunctionInBackground("addFriendToFriendsRelation", withParameters: ["friendRequest": friendRequest.objectId]) { (object:AnyObject!, error: NSError!) -> Void in
        let friendsRelation: PFRelation = PFUser.currentUser()!.relationForKey("friends")
         friendsRelation.addObject(fromUser)
             self.currentUser.saveInBackgroundWithBlock({ (succeeded: Bool, error: NSError!) -> Void in
                 if succeeded {
                 } else {
            }
        })
    }
}

After implementing the function I was required to add "!" to the objectId in the parameter to unwrap it. However, doing this leaves me with the error:

Cannot convert value of type '(AnyObject!, NSError!) -> Void' to expected argument type 'PFIdResultsBlock?'

What must I change in order to call this function?


Solution

  • The PFIdResultsBlock corresponds to the following signature (AnyObject?, NSError?) -> Void so try to change your code to this:

    let friendRequest: PFObject = self.friendRequestsToCurrentUser[sender.tag] as PFObject
    let fromUser: PFUser = friendRequest[FriendRequestKeyFrom] as PFUser
    
    //call the cloud code function that adds the current user to the user who sent the request and pass in the friendRequest id as a parameter
    PFCloud.callFunctionInBackground("addFriendToFriendsRelation", withParameters: ["friendRequest": friendRequest.objectId]) { (object:AnyObject?, error: NSError?) -> Void in
        let friendsRelation: PFRelation = PFUser.currentUser()!.relationForKey("friends")
        friendsRelation.addObject(fromUser)
        self.currentUser.saveInBackgroundWithBlock({ (succeeded: Bool, error: NSError!) -> Void in
            if succeeded {
    
            } else {
    
            }
        })
    }