IOS JSON parsing - ios

I am an iOS beginner. I want to test open source application UBER prototype . When I have launched successfully the application on my Mac I have got the problem (signing up for this ) . I guess there is a problem with data base settings .
Error :
Failed to run command eventually with error: Error
Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with
array or object and option to allow fragments not set."
UserInfo={NSDebugDescription=JSON text did not start with array or
object and option to allow fragments not set.}
Could you give me advice how to fix it? The link for the project is here.

I think you have to set option value to NSJSONReadingAllowFragments. Maybe you have set something else!
Try to look something similar like this in your code:
id json = [NSJSONSerialization JSONObjectWithData:contentOfLocalFile options:NSJSONReadingAllowFragments error:&deserializingError];
And please update the question with the JSON format you are getting?

Related

JSON text did not start with array or object

Working with an iOS app managing data on a Parse-Server (/Heroku).
I have the following issue when trying to save data.
Here is the code for the function where the problem happens:
func saveDataBlockOnline(_ dico: [String:String]) {
let psvClassName = "Goodies",
dataUnit=PFObject(className: psvClassName,
dictionary: dico)
dataUnit.saveInBackground {
(succeeded:Bool, error:Error?) in
if succeeded {
// Do something useful.
} else {print("\(#function) Error:\(error ?? "" as! Error)")}
}
}
Here is the error I get:
saveDataBlockOnline Error:Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
I guess I am getting some JSON answer that I don't use properly. So how should I modify the code?
There are other posts on the subject, but nothing that I found with a real solution.
A few more details may be useful:
The data saving on the server itself was working. But things started to go wrong when I added some cloud code, namely a Parse.Cloud.beforeSave to have a better control on how things are happening.
The data you want to parse in not in correct format according to error message. Check your dictionary and Object(dataUnit) format

Firebase Crashlytics Custom Log Only Log Single Line

Recently my app has been crashing while trying to deserialize the JSON sent from the server and unfortunately the server doesn't record any log so I can't verify with them. So I decided to log the JSON response for this particular Api, I know that it's a bad practice to log server response but it's the only way I could try to identify the issue, the response for this api is not that long so I think it should be fine.
The issue comes in when I tried to reveal the log and found out it only shows one line in the firebase console as below:
raw response : {
The result I was expecting were something as below,vit shows up nicely in the debug console while developing using CLSNSLogv. I thought it will be the same in firebase console too but it was not the case.
raw response : {
success ={
Status = OK;
Object1 = "test"
Object2 = "test2"
};
}
Below is the code for logging, "value" is a dictionary as below:
value: [String : AnyObject]?
CLSLogv("raw response : %#", getVaList([value!]))
Appreciate your help
This is a Crashlytics issue, my team has been experiencing this issue lately. We were printing dictionary using CLS_LOG in ObjC and we've noticed that it displays only first line of the dictionary.
I've contacted Crashlytics support team, and a guy from there confirmed a bug and told me that he contacted their engineering team for a fix.
You can change the way of logging for now to display everything in single line, or log by log, or you can wait for a fix.
You can convert the response to JSON using JSONSerialization and then remove all the carriage returns so that it's all one line. If you log that modified value it should appear correctly in the Crashlytics logs.

When I am update any field in parse database, I'm getting following error from parse database

Updating any field in parse database I'm getting below error very randomly,
My configuration in the AppDelegate looks like:
[Parse initializeWithConfiguration:[ParseClientConfiguration configurationWithBlock:^(id<ParseMutableClientConfiguration> configuration) {
configuration.applicationId = #"wrWJqA47ZvZA27X26HsJzDxc5xxxxxxx";
configuration.clientKey = #"hOhqpoIVK17joL6GiBGD54XIxxxxxx";
configuration.server = #"https://parse.nightlifexp.com/parse";
}]];
You can see my code for updating parse database in the following link:-https://dpaste.de/Fhrk
The interesting thing is Parse.Cloud.beforeSave function works as expected.Only when I requested data back, this issue appears very randomly.
Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
No proper solution found for this parse database error.Anyone can help me how to solve this problem?
Thanks in advance.
The problem is that your JSON is not an array it has nothing to do with your Objective-c code , but the input from your server is wrong.
I think your solution should be on parse.com .

iOS POST doesn't work on HTTPS

I have some code that works fine with HTTP, but fails with (null) value returned from the NSJSONObjectserialization-thing on HTTPS.
I tried converting the received data to string, and it comes out to log as valid JSON. I validated it also to be sure. All good. The HTTPS certificate is valid, but I did try implementing the callbacks for invalid certs also, no change.
The EXACT same configuration works perfectly on HTTP, and if I go to the browser and input the same POST (I even tried removing the POST and just have the server return JSON no matter what you input) I get valid JSON also.
I tried converting the received data to an array and grab the first object in the array - didn't work either. I tried changing http headers in different configurations (application/json) etc. No dice.
Error code is Cocoa 3840. This error means, as far as I can tell, invalid JSON. HOW is this possible? It says character 3 is bad?
Any suggestions? I Googled the best I could but all I can find is "https and http should work in the same way" more or less.
Certificate is validated by RapidSSL.
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:_responseDataNews options:kNilOptions error:&error];
_responseDataNews is the object that gets filled by didReceiveData delegate - and this exact config works on HTTP. What the #€%*# am I doing wrong here? It's driving me insane.
Exact error is:
Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (JSON text did not start with array or object and option to allow fragments not set.) UserInfo=0xbb2cde0 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
If I enable fragment option:
Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Invalid value around character 3.) UserInfo=0xb939ab0 {NSDebugDescription=Invalid value around character 3.}
JSON looks like: {"r":1,"n":"Text here"}
And no, "text" contains no funky characters. This is the actual JSON value I'm testing.
Edit: NSLog of the data object reveals:
efbbbfef bbbfefbb bfefbbbf efbbbf7b 22687322 3a5b7b22 75736572 223a2254
65737465 73656e22 2c227363 6f726522 3a223233 3032227d 5d7d
(with JSON: {"hs":[{"user":"Testesen","score":"2302"}]} )
Edit: ... Okay, as it turns out, now it doesn't work on HTTP either, so it must be after changing the SSL setup or something on the server that it broke!? HTTP returns the exact same (invalid) data object :(
You report that the NSData for your string is:
<efbbbfef bbbfefbb bfefbbbf efbbbf7b 22687322 3a5b7b22 75736572 223a2254
65737465 73656e22 2c227363 6f726522 3a223233 3032227d 5d7d>
The ef bb bf is a byte order mark for a UTF-8 string. But if you have a BOM, you should have only one, and you have five of them.
If you're creating this response programmatically, you may have some server function that is called multiple times that is adding this BOM repeatedly. The BOM should appear only once (if at all), and the fact that it's appearing multiple times indicates a problem in your server code.
If you created this file manually, you might want to edit the hex data. Use whatever hex editor you want to fix this. For example, if you want to edit this file with Xcode, you can add it to your Xcode project and then right click on the file and choose "Open as..." - "Hex".
Okay - it turns out this had nothing to do with HTTPS anyway.
For some reason I cannot really understand, my php script was prefixing invalid characters after I restructured it to use only 1 .php file that responds to POST, includes all other .php files and returns the appropriate function depending on what you POST - of course I tried to just make it call one of the functions without POSTing anything, so that I could exclude POST errors from troubleshooting.
After I changed it so I request the specific file depending on what I want to do on the server - get news, get users, get score, whatever, like server.com/getscore.php instead of just server.com + POST data to get score, it works without issue and the JSON response is valid.
I don't really know how .php messes this up, but SOMETHING goes wrong. I tried enabling "Show all characters" in Notepad++, but I don't see anything funky anywhere. I made sure all .php files are encoded in UTF-8 also.

iOS NSJSONSerialization of JPG image encoded binary data from mongodb

I think I need some assistance in figuring out the correct NSJSONSerialization option to make my problem go away.
On my app I allow the user to select an image from the gallery - the image undergoes the following:
NSData *imageData = UIImageJPEGRepresentation(self.profileImageView.image, 0.0);
then
NSString *stringOfImageData = [imageData base64EncodedStringWithOptions:0];
before it is serialized like this:
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:postDict
options:NSJSONWritingPrettyPrinted
error:&error];
and then sent to my REST API. I then decode it in python using base64 like so:
profileImageData = base64.b64decode(request.json['image'])
It is then loaded in GridFS (mongodb). On extracting the data to send back to the app I first encode in base to base64 before using dumps() to send it back:
dumps(base64.b64encode(fs.get_last_version(request.json['userID']).read()))
Within iOS after receiving the data it goes through the below de-serialization:
[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:&error]
I have narrowed by problem to the last NSJSONSerialization command. After the data is received by the app it is able to print to screen. After the Serialization I get a 'nil' :(
The Serialization and De-Serialization has been working great for strings, integers etc - it just doesn't work when I'm trying to move image data.
Thanks
EDIT: I am able to run a curl request against the API and then using an online base64 to image converter I can see my image. So it definitely means the issues is with the iOS side of decoding a json encoded base64 string.
EDIT: When I repeatedly run the deserialization - every 20th time or so the data is correctly converted. I think the solution might have to be to break up the data coming in.
EDIT: Error:
parsed error:Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn’t be completed. (Cocoa error 3840.)" (Unterminated string around character 17.) UserInfo=0x109c08790 {NSDebugDescription=Unterminated string around character 17.}
What you don't say is how you are receiving the data. My guess is you are trying to decode the data before you receive all of it, but since I don't know how it's a guess.
To better understand what's going on, try logging the size and hash of the data, to see if the length varies. You can also save each received data object to the file system - put them in the Documents folder and you can access them from your Mac. If the size never varies you will then have to compare a good data object to a bad one.
In fact you can write a little code to save an image as data and a base64 string, upload it, then pull it back, and save it. Now compare the data and strings. Once you find a difference, then look at. What is its offset from the start? How is it different?
When you understand this all you will be able to fix it.

Resources