I have a webview from which I'm calling a method that returns result of JSON.stringify();
Then it is stored in database and used later to restore state of the page in webview.
NSString *data = [self.browser stringByEvaluatingJavaScriptFromString:@"course.serialize();"];
[self.course storeRawSerializedData:data];
when it is retrieved from database (Core Data) I'm injecting it into loaded html page source like so:
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
if(_data){
NSString* content = [[NSString alloc] initWithData:_data
encoding:NSUTF8StringEncoding];
_data = nil;
_jsReady = YES;
NSString *data = @"";
if(self.course.returnRawSerializedData){
data = [data stringByAppendingString:@"<script type=\"text/javascript\">var restoreData=%@;</script>"];
data = [NSString stringWithFormat:data, self.course.returnRawSerializedData];
}
//inject extra content to the page
content = [data stringByAppendingString:content];
//load modified HTML string
[self.browser loadHTMLString:content baseURL:_url];
}
}
The problem is with JSON being invalid after this trip:
the json returned by webview is:
{"status":"incomplete","data_json":"{\"colour\":\"#000000\"}"}
and after injecting it looks like this:
<script type=\"text/javascript\">var restoreData={"status":"incomplete","data_json":"{\"colour\":\"#000000\"}"};</script>
The page returns the SyntaxError: JSON parse error: Unexpected identifier "object"
When I wrap it with single or double quotes in stringByAppendingString method then page returns the SyntaxError: JSON parse error: Expected '}'
It works when I escape all double quotes (manually) but I don;t know how to do it programatically, I expected that string returned from stringByEvaluatingJavaScriptFromString will be already escaped to be used within double quotes.