我的应用正在初始化并检查文件,如果存在,则将内容作为json读取并解析它。在Android中这一切都运行正常,但在iOS中,相同的文件读取/解析功能以某种方式读取文件内容两次并将它们存储为无效的json对象,因此解析它失败。
//调用要读取的文件;
// filename //dir //success //fail //next step
readFromFile('userdata.json', 0, yesFile(0), errRFF(1052), checkRegister);
//读取文件;
function readFromFile(fileName, dir, success, error, doRegister) {
if (dir == 0) {
var filePath = cordova.file.dataDirectory ;
// Android: file:///data/data/com.appName/files/
// iOS: NoCloud/
} else if (dir == 1) {
var filePath = cordova.file.applicationDirectory ;
// Android: /project/platforms/android/assets/
// iOS: appname.app/
}
window.resolveLocalFileSystemURL(filePath + fileName, function (fileEntry) {
fileEntry.file(function (file) {
var reader = new FileReader();
console.log("A") ;
reader.onloadend = function (e) {
console.log("B :" +this.result)
// in iOS only, somehow `this.result` getting file contents TWICE
// B : { ..json values #1...correct..
// }{ ..json values #1 again...not correct..
// }
// this is causing a malformed json object
//
// in Android console prints out just:
// B : { ..json values #1...correct..
// }
// as a result, in iOS only, passing parsed JSON to success is failing
success(JSON.parse(this.result),doRegister);
console.log("C") ;
};
reader.readAsText(file);
}, function(e) {error(fileName,e,doRegister)}) ;
},function(e) {error(fileName,e,doRegister)});
}