关于iOS版本远程通知保存信息(About save information from remote

2019-10-20 20:41发布

我有一个结构推送通知

{
    "aps":
    {
        "alert": "Hello, world!",
        "sound": "default",
        "funcId": "abc"  <-- this key i add more
    }
}

我想存储的关键“FUNCID”值后使用应用程序收到<br/>通知(应用程序状态backgound或杀死),如:

-(void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary*)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler
{
   NSString *sFuncID = [[userInfo objectForKey:@"aps"] objectForKey:@"funcId"];
   [[NSUserDefaults standardUserDefaults] setValue:sFuncID forKey:Key_ID_notification];
   [[NSUserDefaults standardUserDefaults] synchronize];
}

我曾尝试使用NSUserDefaults存储这个值,但是当应用程序在后台状态和杀害,此值不存储。 如何存储vaule从远程通知时所使用的应用程序重新启动?

谢谢大家的支持!

Answer 1:

你将不得不处理推送通知在2种不同的方法,因此,你必须保存2种不同方法的价值。 您还需要确保用户信息 保存值/对象到之前NSUserDefaults

该代码是一样的东西如下: -

//Receive Push Notification when the app is active in foreground or background
- (void)application:(UIApplication *)application 
           didReceiveRemoteNotification:(NSDictionary *)userInfo {

  if(userInfo){
   //TODO: Handle the userInfo here
    NSString *sFuncID = [[userInfo objectForKey:@"aps"] objectForKey:@"funcId"];
    [[NSUserDefaults standardUserDefaults] setValue:sFuncID forKey:Key_ID_notification];
    [[NSUserDefaults standardUserDefaults] synchronize];
   }

}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    //Get the push notification when app is not open
    NSDictionary *remoteNotif = [launchOptions objectForKey: UIApplicationLaunchOptionsRemoteNotificationKey];

    if(remoteNotif){
        [self handleRemoteNotification:application userInfo:remoteNotif];
    }

    return YES;
}

-(void)handleRemoteNotification:(UIApplication*)application userInfo:(NSDictionary*)userInfo{

    if(userInfo){
   //TODO: Handle the userInfo here
    NSString *sFuncID = [[userInfo objectForKey:@"aps"] objectForKey:@"funcId"];
    [[NSUserDefaults standardUserDefaults] setValue:sFuncID forKey:Key_ID_notification];
    [[NSUserDefaults standardUserDefaults] synchronize];
   }
}


Answer 2:

您不能保存到NSUserDefaults的,因为你没有权限。

创建使用的NSFileManager另一个文件,并设置适当的文件权限。

然后,你就可以收到通知时写入该文件。



文章来源: About save information from remote notification in ios