IOS之UI状态保持与恢复

为了实现点击Home键使程序退出,可以在设置属性*-info.plist修改Application does not run in background属性值为YES

IOS之UI状态保持与恢复

为实现UI的状态保持和恢复,包括APP层面和storyboard层面,首要条件就是需要在AppDelegate.m文件添加以下两个方法。

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

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

 1.APP层面

          在APPDelegate.m中添加如下代码:

//本例子为记录上一次退出的时间,在下一次打开时显示出来
- (void)application:(UIApplication *)application willEncodeRestorableStateWithCoder:(NSCoder *)coder {
    // 获取系统当前时间
    NSDate *date = [NSDate date];
    NSTimeInterval sec = [date timeIntervalSinceNow];
    NSDate *currentDate = [[NSDate alloc] initWithTimeIntervalSinceNow:sec];
    
    //设置时间输出格式:
    NSDateFormatter *df = [[NSDateFormatter alloc] init ];
    [df setDateFormat:@"yyyy年MM月dd日 HH小时mm分ss秒"];
    NSString *na = [df stringFromDate:currentDate];
    
    
    [coder encodeObject:na forKey:@"lastShutdownTime"];
    
    NSLog(@"application willEncodeRestorableStateWithCoder 时间为:%@", na);
    
    }

- (void)application:(UIApplication *)application didDecodeRestorableStateWithCoder:(NSCoder *)coder {
    NSString * currentTime = [coder decodeObjectForKey:@"lastShutdownTime"];
    AppUtils *appUtils = [AppUtils alloc];
    if (currentTime) {
        [appUtils showDialog:@"上次关闭时间" message:currentTime];
    }
}


//附带AppUtils类文件
//AppUtils.h
#import <Foundation/Foundation.h>

@interface AppUtils : NSObject

- (void)showDialog:(NSString *)title message:(NSString *)message;

@end

//AppUtils.m
#import "AppUtils.h"

@implementation AppUtils

- (void)showDialog:(NSString *)title message:(NSString *)message{
    UIAlertView *alert = [[UIAlertView  alloc]
                                        initWithTitle:title
                                        message:message
                                        delegate:nil
                                        cancelButtonTitle:@"OK"
                                        otherButtonTitles:nil];
    [alert show];
}

@end

 2.storyboard层面

(1)选择指定的storyboard的ViewController,将其restorationID设置为viewController


IOS之UI状态保持与恢复
 

(2)添加下面的方法,实现退出时保存文本框的文本信息。

-(void)encodeRestorableStateWithCoder:(NSCoder *)coder
{
    NSLog(@"encodeRestorableStateWithCoder");
    [super encodeRestorableStateWithCoder:coder];
    [coder encodeObject:self.editText.text forKey:@"kSaveKey"];
}

-(void)decodeRestorableStateWithCoder:(NSCoder *)coder
{
    NSLog(@"decodeRestorableStateWithCoder");
    [super decodeRestorableStateWithCoder:coder];
    self.editText.text = [coder decodeObjectForKey:@"kSaveKey"];
}