我正在尝试通过解析启用推送通知。如果已经有用户缓存并登录到应用程序,则解析通知代码将起作用。但是,如果我注销并尝试注册新用户,应用程序就会崩溃,并且收到一条错误消息:“NSInvalidArgumentException”,原因:“不能对 PFObject 上的键或值使用 nil”。使用 NSNull 作为值。'...我相信问题出在应用程序委托中的 didRegisterForRemoteNotificationsWithDeviceToken 方法。由于没有当前用户登录,因此当应用程序尝试创建 PFInstallation 时,所有关联字段都返回 nil。我在运行 PFInstallation 代码之前尝试使用 if 语句检查 currentUser,但应用程序仍然崩溃。我需要在注册后注册通知,但我不知道如何做到这一点,因为 didRegisterForRemoteNotificationsWithDeviceToken 需要在应用程序委托中发生。任何建议或解决方案都很感激。我的代码片段如下。谢谢!
编辑:此代码现在可以运行!
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)newDeviceToken
{
PFInstallation *currentInstallation = [PFInstallation currentInstallation];
if ([PFUser currentUser] != nil)
{
currentInstallation[@"currentUser"]=[PFUser currentUser];
}
else
{
[currentInstallation removeObjectForKey:@"currentUser"];
}
[currentInstallation setDeviceTokenFromData:newDeviceToken];
[currentInstallation saveInBackground];
}
用于发送推送通知
- (IBAction)send:(id)sender
{
PFQuery *userQuery = [PFUser query];
[userQuery whereKey:@"objectId" equalTo:self.recipient.objectId];
PFQuery *query = [PFInstallation query];
[query whereKey:@"user" matchesQuery:userQuery];
NSString *sendingUser = self.currentUser.username;
NSString *message = [NSString stringWithFormat:@"from %@: \n %@", sendingUser,self.message.text];
PFPush *push= [[PFPush alloc]init];
[push setQuery:query];
[push setMessage:message];
[push sendPushInBackground];
NSLog(@"Message sent!");
[self dismissViewControllerAnimated:NO completion:nil];
}
您仍然可以在没有当前用户的情况下注册安装,但必须确保该用户已从注册中删除 -
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
// Store the deviceToken in the current installation and save it to Parse.
PFInstallation *currentInstallation = [PFInstallation currentInstallation];
if ([PFUser currentUser] != nil)
{
currentInstallation[@"currentUser"]=[PFUser currentUser];
}
else {
[currentInstallation removeObjectForKey:@"currentUser"];
}
[currentInstallation setDeviceTokenFromData:deviceToken];
[currentInstallation saveInBackground];
}
然后,无论您在何处处理登录/注销事件,都可以更新当前安装记录。例如 -
-(void) loggedIn
{
PFInstallation *currentInstallation=[PFInstallation currentInstallation];
currentInstallation[@"currentUser"]=[PFUser currentUser];
[currentInstallation saveInBackground];
}
-(void) notLoggedIn
{
PFInstallation *currentInstallation=[PFInstallation currentInstallation];
[currentInstallation removeObjectForKey:@"currentUser"];
[currentInstallation saveInBackground];
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)