Search code examples
iosuiwebviewlocal-storage

Read local storage when iOS app enters background


Objective-c is extremely new to me:

The method below triggers when my iphone app moves to the background. In that moment I want to grab the items in UIWebView's local storage and store in the app.

I'm getting the error "No known class for selector 'stringByEvaluatingJavaScriptFromString:jsString'". How do I inject this dependency into this function while still keeping 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"]);
}

Solution

  • The code [UIWebView stringByEvaluatingJavaScriptFromString:] is attempting to invoke a CLASS method called stringByEvaluatingJavaScriptFromString on the UIWebview class. The stringByEvaluatingJavaScriptFromString method is an instance method. You need to send that message to an instance of UIWebView, not the class.

    If you have a property myWebView then you'd use the code:

    [self.myWebView stringByEvaluatingJavaScriptFromString:]
    

    That sends the stringByEvaluatingJavaScriptFromString message to the instance of UIWebview pointed to by the self.myWebView property. That's what you want.