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

时间:2016-12-01 22:36:13

标签: ios uiwebview local-storage

Objective-c对我来说是一个新手:

当我的iphone应用移动到后台时,下面的方法会触发。在那一刻,我想抓住UIWebView的本地存储中的项目并存储在应用程序中。

我收到错误"No known class for selector 'stringByEvaluatingJavaScriptFromString:jsString'"。如何在保留UIApplication的情况下将此依赖项注入此函数?

- (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"]);
}

1 个答案:

答案 0 :(得分:1)

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

如果您有myWebView属性,那么您将使用代码:

[self.myWebView stringByEvaluatingJavaScriptFromString:]

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