我遇到了我的cordova应用程序的问题,在应用程序更新后,localStorage被清除。我现在尝试使用cordova的FileWriter和FileReader将一些基本用户数据保存到文本文件中。
在某些时候cordova更新并且这些方法现在需要一个插件来读写文件:https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/index.html
因为我的实时iOS应用程序使用旧版本的cordova,所以必须使用FileWriter编写。我的应用更新(不是直播)使用较新版本的cordova,因此必须使用该插件。
------找到可能的解决方法,请参阅下面的更新------
尝试读取文件时,我在xcode中看到以下错误:
017-01-26 17:58:52.990 MyApp [40355:2892997]错误:方法'你好'没有在插件'文件'中定义 2017-01-26 17:58:52.991 MyApp [40355:2892997] - [CDVCommandQueue executePending] [Line 142] FAILED pluginJSON = [“File1875336264”,“File”,“hello there”,[“cdvfile:// localhost /持久性/ player_data.txt”,NULL,NULL]]
注意:我在iOS模拟器运行时在Safari控制台中运行以下代码,只是为了方便
我写文件的代码
(function() {
var onFail = function(err) {
alert('write action failed!');
alert(err.code);
};
var onGotFS = function(fileSystem) {
alert( 'gotFS' );
fileSystem.root.getFile("player_data.txt", {create: true}, onGotFileEntry, onFail);
};
var onGotFileEntry = function(fileEntry) {
alert( 'gotFileEntry, path: ' + fileEntry.fullPath );
fileEntry.createWriter(onGotFileWriter, onFail);
};
var onGotFileWriter = function(writer) {
alert( 'gotFileWriter' );
writer.onwrite = onFileWritten;
writer.onerror = onFail;
var data = "hello there";
alert( 'writing data: ' + data );
writer.write( data );
};
var onFileWritten = function(evt) {
alert( "saveTokenToFile SUCCESS!" );
};
// start process of looking up file system and writing
alert( 'requesting file system ...' );
window.requestFileSystem(LocalFileSystem.PERSISTENT, 1024, onGotFS, onFail);
})();
我的阅读文件的代码:
(function() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {
fs.root.getFile("player_data.txt", { create: true }, function (fileEntry) {
fileEntry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function() {
alert("Success");
console.log(evt.target.result);
};
reader.onerror = function() {
console.log("reader error");
};
reader.readAsText(file);
}, onErrorReadFile);
});
}, onErrorLoadFs);
var onErrorReadFile = function(){
console.log("error reading file");
}
var onErrorLoadFs = function() {
console.log("request file system has failed to load.");
}
})();
更新
如果遇到其他人,我确实找到了一种方法来读取保存的文件。 fileEntry对象具有指向已保存文件的URL路径。为了访问文件上的数据,我将该URL传递给jQuery.getJSON,它为我们提供了一些可读的json。
readDataFromFile: function(){
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function (fs) {
fs.root.getFile("player_data.txt", {}, function (fileEntry) {
var entryURL = fileEntry.nativeURL;
jQuery.getJSON(entryURL, function(data) {
console.log(data);
}).fail(function(){
console.log("file found, but contents were empty");
});
}, onErrorGetFile);
}, onErrorLoadFs);
var onErrorLoadFs = function() {
console.log("request file system has failed to load.");
};
var onErrorGetFile = function() {
console.log("requested file can not be read or does not exist");
};
}