【问题标题】:Loading UIWebview with last accessed page使用最后访问的页面加载 UIWebview
【发布时间】:2014-04-16 08:45:44
【问题描述】:

我正在开发一个应用程序,我需要在其中加载带有上次访问网页的 UIWebview。 我将最后一页 URL 存储为:

self.currentURL = [self.webView stringByEvaluatingJavaScriptFromString:@"window.location.href"];

效果很好。

但问题是,我不确定如何保存这个值,这样一旦我退出 UIWebview 并重新启动它,这个值就不是 nil。

所以,我尝试将其存储在 NSUserDefaults 中,如下所示:

[[NSUserDefaults standardUserDefaults] setObject:self.currentURL forKey:@"currentURL"];

这存储了值,我可以在重新启动 UIWebview 时访问它。

这是我启动 Web 视图的方式:

self.currentURL = [[NSUserDefaults standardUserDefaults] stringForKey:@"currentURL"];

if (self.currentURL) {
    [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.currentURL]]];
}
else {
    [webView loadRequest:[NSURLRequest requestWithURL:url]];
}

效果很好。

现在我面临的问题是,

我有我的应用程序的主屏幕,其中有几个按钮可以打开各种链接(不同的 UIwebview 页面)。我只想在页面已导航并按下相同按钮的情况下使用最后访问的页面打开 UIWebview打开 UIWebView。如果单击任何其他按钮,则不应打开最后访问的页面,而是应打开为该按钮编码的新链接。

有谁知道如何实现这种行为?

P.S:我没有在我的应用程序中使用 XIB。

【问题讨论】:

    标签: ios uiwebview


    【解决方案1】:

    没那么难。假设您有 4 个按钮。

    在NSUserDeafults上分别跟踪每个按钮。

    像这样:

    [[NSUserDefaults standardUserDefaults] setObject:self.currentURL forKey:@"currentURLForButton1"];
    [[NSUserDefaults standardUserDefaults] setObject:self.currentURL forKey:@"currentURLForButton2"];
    [[NSUserDefaults standardUserDefaults] setObject:self.currentURL forKey:@"currentURLForButton3"];
    [[NSUserDefaults standardUserDefaults] setObject:self.currentURL forKey:@"currentURLForButton4"];
    

    在您的 button1 点击操作中:

    self.currentURL = [[NSUserDefaults standardUserDefaults] stringForKey:@"currentURLForButton1"];
    
    if (self.currentURL) {
        [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.currentURL]]];
    }
    else {
        [webView loadRequest:[NSURLRequest requestWithURL:url]];
    }
    

    ....

    ....

    在按钮 4 中单击操作:

    self.currentURL = [[NSUserDefaults standardUserDefaults] stringForKey:@"currentURLForButton4"];
    
    if (self.currentURL) {
        [webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.currentURL]]];
    }
    else {
        [webView loadRequest:[NSURLRequest requestWithURL:url]];
    }
    

    我刚刚描述了一个简单但漫长的过程。您可以使用单个数组来完成此操作。希望这会有所帮助.. :)

    【讨论】:

      【解决方案2】:

      我建议您使用NSURLCache 来存储缓存,然后根据请求的URL 加载缓存。

      【讨论】:

      • 你能推荐一些关于如何实现它的链接或好的教程吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-02
      • 1970-01-01
      相关资源
      最近更新 更多