iOS應用狀態保存和恢復

當應用被後臺Kill掉的時候但願從後臺返回的時候顯示進入後臺以前的內容web

 

在Appdelegate中設置

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

 爲每一個ViewController設置:restorationIdentifier(能夠直接在sb中設置),restorationClassapp

     若是設置了restorationClas則必須遵照UIViewControllerRestoration協議返回恢復時的控制器ide

+ (UIViewController *)viewControllerWithRestorationIdentifierPath:(NSArray<NSString *> *)identifierComponents coder:(NSCoder *)coder{
    UIStoryboard *storybord = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
    UIViewController *controller = [storybord instantiateViewControllerWithIdentifier:@"mywebcontroller"];
     controller.restorationIdentifier = [identifierComponents lastObject];
    controller.restorationClass = [MyWebViewController class];
    return controller;
}

若是未指定代理方法則從Appdelgate中的代理中返回spa

If a view controller has an associated restoration class, the viewControllerWithRestorationIdentifierPath:coder: method of that class is called during state restoration. That method is responsible for returning the view controller object that matches the indicated view controller. If you do not specify a restoration class for your view controller, the state restoration engine asks your app delegate to provide the view controller object instead.代理

在控制器中保存和恢復狀態

//只保存狀態,若是是數據的話保存在文件中如NSUserdefault等
- (void)encodeRestorableStateWithCoder:(NSCoder *)coder{
    //保存開關狀態
    [coder encodeBool:_switchBtn.isOn forKey:@"ison"];
    
    [super encodeRestorableStateWithCoder:coder];
}
- (void)decodeRestorableStateWithCoder:(NSCoder *)coder{
    [super decodeRestorableStateWithCoder:coder];
    //獲取開關狀態
    _switchBtn.on = [coder decodeBoolForKey:@"ison"];
    
}
相關文章
相關標籤/搜索