首页 > ios 状态恢复怎么弄

ios 状态恢复怎么弄

1.看来了好几个例子,还是没搞清楚,每次app第一次运行都会 Warning: Unable to create restoration in progress marker file,并且第一次不会进入decodeRestorableStateWithCoder方法
2.这个不是我想实现的效果,我想实现每次程序后台和关闭的时候自动保存,然后程序启动的时候恢复,第一次也能正常


  1. 状态恢复功能在模拟器上不可用,不好测试,真机没有问题,搞机吧,少年。

  2. 使用NSUserDefaults替代:

    -(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
        //load status when starting
        NSString * statusToRestore = [[NSUserDefaults standardUserDefaults] objectForKey:@"FightingStatus"];
        NSDate *lastUpdated=[[NSUserDefaults standardUserDefaults] objectForKey:@"LastUpdated"];
        NSLog(@"restored:%@ on %@",statusToRestore,lastUpdated);
        return YES;
    
    }
    
    -(void)applicationWillEnterForeground:(UIApplication *)application {
        //restore status when reactive
        NSString * statusToRestore = [[NSUserDefaults standardUserDefaults] objectForKey:@"FightingStatus"];
        NSDate *lastUpdated=[[NSUserDefaults standardUserDefaults] objectForKey:@"LastUpdated"];
        NSLog(@"restored:%@ on %@",statusToRestore,lastUpdated);
    }
    
    -(BOOL)application:(UIApplication *)application shouldSaveApplicationState:(nonnull NSCoder *)coder
    {
        return YES;
    }

    -(BOOL) application:(UIApplication *) application shouldRestoreApplicationState:(nonnull NSCoder *)coder
    {
        return YES;
    }

    -(void)application:(UIApplication *)application willEncodeRestorableStateWithCoder:(nonnull NSCoder *)coder
    {
        //
        //[coder encodeFloat:2.0f forKey:@"Version"];
        //NSLog(@"encode version :2.0f");
        
        //save status when inactive
        NSString * statusToSave=@"Fighting";
        NSDate *lastUpdated = [NSDate dateWithTimeIntervalSinceNow:-3600];
        [[NSUserDefaults standardUserDefaults] setObject:statusToSave forKey:@"FightingStatus"];
        [[NSUserDefaults standardUserDefaults] setObject:lastUpdated forKey:@"LastUpdated"];
        NSLog(@"saved:%@ on %@",statusToSave,lastUpdated);
    }
    
    -(void)application:(UIApplication *)application didDecodeRestorableStateWithCoder:(NSCoder *)coder
    {
        //failed when testing in simulator
        //NSLog(@"Version=%g",[coder decodeFloatForKey:@"Version"]);
    }
【热门文章】
【热门文章】