ios - 当iOS应用程序进入后台时读取本地存储

标签 ios uiwebview local-storage

Objective-c 对我来说非常陌生:

当我的 iPhone 应用程序移至后台时,将触发以下方法。在那一刻,我想抓取 UIWebView 本地存储中的项目并将其存储在应用程序中。

我收到错误“选择器‘stringByEvaluatingJavaScriptFromString:jsString’没有已知的类”。如何在保留 UIApplication 的同时将此依赖项注入(inject)到该函数中?

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.

    //Persist local storage data
    NSLog(@"Persisting local storage since app entering background");

    //Reading local storage item
    NSString *jsString = @"localStorage.getItem('mpo.subdomain');";
    NSString *someKeyValue = [UIWebView stringByEvaluatingJavaScriptFromString:jsString];

    // Store your subdomain in iPhone persistence variable and use it later in the application
    NSUserDefaults *userdefault = [NSUserDefaults standardUserDefaults];
    [userdefault setObject:someKeyValue forKey:@"subdomain"];
    [userdefault synchronize];

    //use of User default
    NSLog(@"User Subdomain %@",[userdefault valueForKey:@"subdomain"]);
}

最佳答案

代码[UIWebView stringByEvaluatingJavaScriptFromString:]正在尝试调用UIWebview类上名为stringByEvaluatingJavaScriptFromString的CLASS方法。 stringByEvaluatingJavaScriptFromString 方法是一个实例方法。您需要将该消息发送到 UIWebView 的实例,而不是类。

如果你有一个属性 myWebView 那么你会使用代码:

[self.myWebView stringByEvaluatingJavaScriptFromString:]

它将 stringByEvaluatingJavaScriptFromString 消息发送到 self.myWebView 属性指向的 UIWebview 实例。那就是你想要的。

关于ios - 当iOS应用程序进入后台时读取本地存储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40921661/

相关文章:

javascript - Web 开发 : localStorage vs. 缓存 HTTP

javascript - 使用javascript跨域本地存储

ios - UIWebview -- "Open/Copy"对话框以错误的方向打开

php - 是否可以从 HTML5 的本地存储中提取数据并保存到服务器数据库?

ios - Objective-C中两个数组的补码

ios - 线程 1 : EXC_BAD_ACCESS (code=EXC_I386_GPFLT)

ios - 如何将字体导入 Xcode 4 界面生成器?

ios - 查找tableView的哪一行是CollectionView

objective-c - 带有分页的全屏 UICollectionView 内的 UIWebView

ios - 为什么我的 webview 提示错误?