如何通过Parse将推送通知发送给特定用户?

时间:2015-07-23 04:52:24

标签: xcode parse-platform push-notification

我已经通过Parse和Apple设置了推送通知,我似乎无法找到向其他用户发送推送通知的直接方式。

对于我的情况,我想在用户向他们发送朋友请求时向用户发送通知。这是我用来保存以请求服务器的代码:

 //get current user
 PFQuery *query2 = [PFUser query];
    [query2 whereKey:@"username" equalTo:pendingFriendName];
    PFUser *userTo = (PFUser *)[query2 getFirstObject];


    PFQuery *query = [PFQuery queryWithClassName:@"Follow"];
    [query whereKey:@"from" equalTo:[PFUser currentUser]];

    // execute the query
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {

                PFObject *follow = [PFObject objectWithClassName:@"Follow"];
                [follow setObject:[PFUser currentUser]  forKey:@"from"];
                [follow setObject:userTo forKey:@"to"];
                [follow saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {

                    if(succeeded)
                    {
                        NSLog(@"success!");
                        [friendAddedLabel setText:@"Friend Added!"];

                    }
                    else
                    {
                        NSLog(@"error");
                    }
                }];

            }
          }];

此外,是否有办法将发送请求的用户的直接引用发送给收到好友请求的用户,这样当用户点击通知而不是通过另一个请求时,它可以快速获取信息查询?

1 个答案:

答案 0 :(得分:2)

首先,您必须将当前用户存储到Installation类中,然后使用PFInstallation Query和PFPush发送推送通知。

//save the user into installtion class.
PFInstallation *currentInstallation = [PFInstallation currentInstallation];
if ([PFUser currentUser].objectId)
{
       currentInstallation[@"user"] = [PFUser currentUser];
       currentInstallation.channels = @[[NSString stringWithFormat:@"user_%@",[PFUser currentUser].objectId]];
        NSLog(@"Saving Installation channel = %@",currentInstallation.channels);
        [currentInstallation saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) 
           {
                 NSLog(@"Current installation updated: Error: %@",error);
           }];
}

//Then send push notification to particular user.
PFQuery *queryInstallation = [PFInstallation query];
[queryInstallation whereKey:@"user" equalTo:user];

PFPush *push = [[PFPush alloc] init];
[push setQuery:queryInstallation];
NSDictionary * dic = @{@"alert" : text,@"badge" : @"Increment" , @"sender" : [PFUser currentUser].objectId ,@"MediaId" : mediaObject.objectId};
[push setData:dic];

[push sendPushInBackgroundWithBlock:^(BOOL succeeded, NSError *error)
 {
     if (error != nil && !succeeded)
     {
         NSLog(@"SendPushNotification send error.");
     }
     else
     {
         NSLog(@"SendPushNotification send success.");
     }
 }];
相关问题