简体   繁体   English

设置NSUserDefault当应用程序取消或不活动时

[英]Set NSUserDefault When app is canceled or inactive

I receive a push notification when the my app is closed or canceled. 我的应用程序关闭或取消时,我会收到推送通知。 Is there a way to set an nsuserdefault when this happens? 发生这种情况时,有没有办法设置nsuserdefault? I know if a user taps the notification or opens the app from the notification you can check if the app was inactive or canceled but what if they don't open the app from the notification but rather just launch the app by clicking on the icon? 我知道用户是否可以点击通知或从通知中打开应用程序,您可以检查应用程序是否处于非活动状态或已取消,但如果他们不从通知中打开应用程序而是通过单击图标启动应用程序,该怎么办?

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

I know this method is called but it seems like I can not save to nsuserdefaults if the app is terminated or canceled. 我知道此方法被调用,但是如果应用终止或取消,似乎无法保存到nsuserdefaults。

If the app is closed or inactive and user opens the app through the icon , you will get the remote notification in "didFinishLaunchingWithOptions" method if any notification is available , there you can set you userdefault if you want . 如果该应用程序已关闭或处于非活动状态,并且用户通过图标打开了该应用程序,则如果有可用通知,您将在“ didFinishLaunchingWithOptions”方法中收到远程通知,如果需要,您可以在其中设置userdefault。 Here is the code to get the remote notification in "didFinishLaunchingWithOptions" 这是在“ didFinishLaunchingWithOptions”中获取远程通知的代码

 (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {


if (launchOptions) { //launchOptions is not nil
    NSDictionary *userInfo = [launchOptions valueForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
    NSDictionary *apsInfo = [userInfo objectForKey:@"aps"];

    if (apsInfo) { //apsInfo is not nil
        [self performSelector:@selector(postNotificationToPresentPushMessagesVC) 
                   withObject:nil
                   afterDelay:1];
    }
}
return YES;
}

For more help please visit this link @staticVoidMan have answered it very well . 如需更多帮助,请访问此链接 @staticVoidMan已经很好回答了。

Hope this Helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM