如果您只是想在视图之间保存页面地址,则无需使用 NSUserDefaults 或状态恢复。 (如果您希望在应用程序使用之间保存数据,那么可以,您可以使用 NSUserDefaults 存储 url 字符串。)
要将值存储在您的应用委托中以供全局访问,请在您的应用委托的 .h 中声明该变量:
@property (nonatomic) NSUrl *currentUrl;
要访问类中的变量,请在 .m 中创建应用委托的实例:
#import "ViewController.h"
#import "AppDelegate.h"
@interface ViewController ()
@end
@implementation ViewController
AppDelegate *mainDelegate;
- (void)viewDidLoad
{
mainDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
然后代替使用:
NSURL *url = [NSURL URLWithString:@"https://www.mywebsite.com"];
NSURLRequest *requestURL = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestURL];
在打开webView 之前初始设置currentUrl 值:
mainDelegate.currentUrl = [NSURL URLWithString:@"https://www.mywebsite.com"];
在每个 webView 打开之前,将 NSUrlRequest 初始化为:
NSURLRequest *requestURL = [NSURLRequest requestWithURL:mainDelegate.currentUrl];
最后,要在关闭时存储每个webView 的当前地址,请使用:
mainDelegate.currentUrl = webView.request.URL;