TheCocoaProject / cordova-plugin-nativestorage

Cordova plugin: Native storage of variables in Android, iOS and Windows
http://thecocoaproject.github.io/
Apache License 2.0
292 stars 106 forks source link

getItem returns JSON_ERROR trying to get a value stored using objective c #140

Open kperdomoc opened 5 years ago

kperdomoc commented 5 years ago

So Im rebuilding this iOS app with ionic and would like to migrate the old user data stored using NSUserDefaults. For example, the old app would store the username like this:

[defaults setObject:user.username forKey:@"username"];

And Im trying to get that back using getItem:

this.nativeStorage.getItem('username').then( data => { console.log("USERNAME: ", data) }, error => { console.log("ERROR: ", JSON.stringify(error)) }

This crashes and produces the following error:

code: 5 (JSON_ERROR) source: JS exception: {"line":400,"column":25,"sourceURL":"http://10.10.1.6:8100/plugins/cordova-plugin-nativestorage/www/mainHandle.js"}

Well, the exception tells the line number thats crashing. Opened the mainHandle file and turns out to be when trying to parse the result data from the device.

try { obj = JSON.parse(data); success(obj); } catch (err) { error(new NativeStorageError(NativeStorageError.JSON_ERROR, "JS", err)); }

I have debugged the plugin's ios code and it is indeed getting the data from the device storage. So the data exists and it's being returned fine. The problem comes when JS code tries to handle that using JSON.parse.

In my tests, lets say the stored value is username = 'username@domain.com', then the parsing will fail. But if i do setItem(username, "username@domain.com"), then retrieve that, I get username = '"username@domain.com"' (notice the double quotes included). So, seems that the plugin won't be able to retrieve values that are not JSON-parsable.