我们只是做了类似的事情。我们的旧原生应用程序使用的是 CoreData。我们在 MainViewController 的 webViewDidFinishLoad 委托方法中添加了一个检查,以查看是否存在现有数据库。如果是,那么我们加载数据库,通过 localStorage 转换内容以供使用,然后设置一个标志,以便它不会再次尝试导入它。这是将其传输到 localStorage 的代码段。首先,我们将要传输的信息放入 NSMutableString 中,但将其格式化为 javascript 字典
NSMutableString *dict = [NSMutableString string];
[dict appendString:@"{"];
[dict appendFormat:@"'notes':'%@'", notes];
[dict appendFormat:@",'date':'%f'",seconds];
[dict appendFormat:@",'count':'%d'",[ss.count intValue]];
[dict appendFormat:@",'weather':'%@'",wx];
[dict appendFormat:@",'location':'%@'",ss.event.location.name];
[dict appendFormat:@",'latitude':'%@'",[ss.event.location.latitude stringValue]];
[dict appendFormat:@",'longitude':'%@'",[ss.event.location.longitude stringValue]];
[dict appendString:@"}"];
然后我们像这样将它传递给javascript:
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"importMyOldData(%@);",dict]];
这有效地调用了 javascript 方法,并将项目字典传递给它。然后你可以直接使用 Javascript 将其放入本地存储中,例如:
function importMyOldData( oldData )
{
// if you want to inspect each item
var notes = oldData.notes;
localStorage.setItem( "NoteKey", notes );
// if you want to dump the whole thing
localStorage.setItem( "MyKey", JSON.stringify(oldData) );
}