About save information from remote notification in ios

*爱你&永不变心* 提交于 2019-12-11 10:04:43

问题


I have a push notification with struct

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

I want to store value of key "funcId" to use after app recives notification (app in state backgound or killed) like:

-(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];
}

I had try use NSUserDefaults to store this value, but when app in state background and killed this value not store. How to store vaule from remote notification to use when app relaunch?

Thanks all support!


回答1:


You will have to handle Push Notification in 2 different methods, so, you will have to save the value in 2 different methods. You will also need to make sure that the userInfo is not nil before saving the value/object into NSUserDefaults.

The code is something like below:-

//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];
   }
}



回答2:


You cannot save to NSUserDefaults, since the you don't have the permission.

Create another file using NSFileManager, and set the proper file permission.

Then you'll be able to write to that file when receiving notification.



来源:https://stackoverflow.com/questions/25619259/about-save-information-from-remote-notification-in-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!