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!
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];
}
}
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.