The Operation couldn't be completed. (Cocoa error: 3840.) - objective-c

I am trying to parse JSON for an ios 6 app, but can't seem to get it to work. I have scoured tons of forums but haven't found a solution that works, that I understand enough to implement, or that applies.
I apologize if there is one that I missed.
First I have a test WebService that as far as I can tell returns valid JSON
http://thetrouthunter.com/SVLocationsAPI.php
Second, here is my Objective-C code:
+ (NSDictionary *)connectToService:(NSString *)query
{
NSError *error = nil;
query = [NSString stringWithFormat:#"%#&format=json&nojsoncallback=1", query];
query = [query stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSData *jsonData = [[NSString stringWithContentsOfURL:[NSURL URLWithString:query] encoding:NSUTF8StringEncoding error:nil] dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *results = jsonData ? [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:&error] : nil;
NSLog(#"locations: %#", results);
if (error)
NSLog(#"[%# %#] JSON error: %#", NSStringFromClass([self class]), NSStringFromSelector(_cmd), error.localizedDescription);
return results;
}
+ (NSArray *)userLocation {
NSString *request = [NSString stringWithFormat:#"http://thetrouthunter.com/SVLocationsAPI.php"];
return [[self connectToService:request] valueForKeyPath:#"locations.location"];
}
The ls NSLog function is printing out the error: "The operation couldn't be completed. (Cocoa error: 3840.)"
I can't figure out why this is the case. I have tried all sorts of things.

You are adding %#&format=json&nojsoncallback=1 to the URL in connectToService:, and that new URL results in a webpage, not the JSON you expect (i.e. http://thetrouthunter.com/SVLocationsAPI.php&format=json&nojsoncallback=1).
It might be useful to log the actual result from the HTTP request so that you can debug this until you get JSON (i.e. prior to calling the serialization functions).

Related

Json deserialization with objective-c failing on copyright symbol

I'm primarily a c# developer but I have been tasked with resolving a bug in an objective-c mac client. I am using nsjsonserialization to serialize the json object.
The bug occurs on deserialization if the json object contains the copyright symbol.
We were using sbjson and I switched to nsjsonserialization and that didn't resolve the issue. I don't know if I am doing it wrong or if I need to use a different serialization library. In c# I could just use newtonsoft. Is there a similarly standard json serialization library for objective-c that I should use?
Here is the serialization code:
-(void)sendMessage:(NSString *)method:(NSDictionary *)inData {
NSDictionary *outData = [[NSDictionary alloc] init];
#try {
JsonServiceComm *newCom = [[JsonServiceComm alloc] init];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#/%#", host, method]];
NSData *json = [NSJSONSerialization dataWithJSONObject:inData options:kNilOptions error:nil];
json = [json subdataWithRange:NSMakeRange(0, [json length] - 1)];
NSString* jsData = [NSString stringWithUTF8String:[json bytes]];
NSString *outData = [newCom userSpaceRequest:url :jsData];
} #catch (NSException* ex) {
NSLog(#"%#", [ex reason]);
}
}
Here is where it is being deserialized:
-(void)handleMessage:(NSString *)messageType message:(NSString *)message {
#autoreleasepool {
NSData *jsMessage = [message dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSDictionary *data = [NSJSONSerialization JSONObjectWithData:jsMessage options:NSJSONReadingMutableLeaves error:&error];
}}
If the data does not contain a copyright symbol, *data is populated with a dictionary of values, however if it does contain the copyright symbol, *data comes out nil. The error returned is "Unexpected end of file while parsing object."
This is resolved. I discovered that the json was being passed through a separate json parser where it was not being utf8 encoded.
Try using options:0 instead of options:NSJSONReadingMutableLeaves
https://developer.apple.com/documentation/foundation/nsjsonreadingoptions/nsjsonreadingmutableleaves?language=objc

How to read Java generated JSON data from Objective C?

I have generated JSON data from Java Restful WebServices and I need to put into the Objective C code. How can I use the JSON data and integrate into Objective C? The IDE has generated the local URL, how can I use the generated JSON data in other machine. Thank you
Have a look at NSURLConnection to retrieve the JSON from your web service. Then you can make use of NSJSONSerialization to parse it.
Use any of the many JSON parsers available. This question compares a few of them: Comparison of JSON Parser for Objective-C (JSON Framework, YAJL, TouchJSON, etc)
You can request the NSData from the URL and then use NSJSONSerialization to interpret it. For example:
NSURL *url = [NSURL URLWithString:#"http://www.put.your.url.here/test.json"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
[NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error) {
NSLog(#"%s: sendAsynchronousRequest error: %#", __FUNCTION__, error);
return;
}
NSError *jsonError = nil;
NSArray *results = [NSJSONSerialization JSONObjectWithData:data options:0 error:&jsonError];
if (jsonError) {
NSLog(#"%s: JSONObjectWithData error: %#", __FUNCTION__, jsonError);
return;
}
// now you can use the array/dictionary you got from JSONObjectWithData; I'll just log it
NSLog(#"results = %#", results);
}];
Clearly, that assumed that the JSON represented an array. If it was a dictionary, you'd replace the NSArray reference with a NSDictionary reference. But hopefully this illustrates the idea.

App crashing because NSArray objectforkey: Objective C

I am trying to parse some Json with Objective C.
My problem is that I am getting the correct json back but when I try parse some of the json my app crashes.
// i will use a code from connect to DB tutorial
NSString *strURL = [NSString stringWithFormat:#"http://www.ddproam.co.za/Central/Asset/AssetsWithSerial?Serial=S00000001"];
// to execute php code
NSData *dataURL = [NSData dataWithContentsOfURL:[NSURL URLWithString:strURL]];
// to receive the returend value
NSString *strResult = [[NSString alloc] initWithData:dataURL encoding:NSUTF8StringEncoding];
NSLog(#"Login response:%#",strResult);
NSError *error;
//parse out the json data
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:dataURL //1
options:kNilOptions
error:&error];
NSArray* defineJsonData = [json objectForKey:#"AssetDesc"]; //2
NSLog(#"value: %#", defineJsonData); //3
Here is my json:
[{"AssetID":1,"AssetName":"Asset 1","AssetDesc":"This is a manually inserted Asset","AssetTypeID":1,"AssetTypeDesc":"This is a manually inserted Asset Type"}]
I am trying to get the AssestName out of the string. I must be doing something wrong.
The whole thing is an array containing a dictionary, not a dictionary containing an array...
This is a very dirty way to get the value you want - you want to write something more safe than this. Try checking the type of class returned before you try to use it...
NSArray* json = [NSJSONSerialization JSONObjectWithData:dataURL //1
options:kNilOptions
error:&error];
NSDictionary* defineJsonData = [json lastObject]; //2
NSLog(#"value: %#", [defineJsonData objectForKey:#"AssetDesc"]); //3

Using NSJSONSerialization for mac

I'm trying to user NSJSONSerialization in a mac app, but i can't get it working, I'm trying to get it to load UserTimeline, and just show the text of the last tweet, and thats it, but I can't seem to find the proper way to use it. the api i have tried to use :
http://api.twitter.com/1/statuses/user_timeline.json?screen_name=AlexTrott_
And
http://twitter.com/statuses/user_timeline/AlexTrott_.json
but neither of them i've had look, this is how i've been trying to use NSJSONSerialization :
NSString *tweets = [NSURL URLWithString:#"http://twitter.com/statuses/user_timeline/AlexTrott_.json"];
NSData *jsonData = [tweets dataUsingEncoding:NSUTF8StringEncoding];
NSError *e = nil;
NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&e];
NSLog(#"%#", json);
that is just what i've been using to see if it's loaded them, but it's been failing me.
I also tried was going to try this method http://www.raywenderlich.com/5492/working-with-json-in-ios-5 however thats solely for iOS and i don't know how i'd get it to work on Mac.
Any links on how to use NSJSONSerialization for mac would be brilliant, or any help with could would also be a major thanks. I tried getting help on the apple developer forums, but no luck there.
NSURL *tweets = [NSURL URLWithString:#"http://twitter.com/statuses/user_timeline/AlexTrott_.json"];
//NSData *jsonData = [tweets dataUsingEncoding:NSUTF8StringEncoding];
//NSMutableArray *json = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&e];
NSData *jsonData=[NSData dataWithContentsOfURL:tweets];
NSError *e = nil;
id yourJsonData=[NSJSONSerialization JSONObjectWithData:jsonData options:
NSJSONReadingMutableContainers error:&error];
NSLog("%#",yourJsonData );//you must get a json object here
//let's assume you need to get the key kalled user_name from your JSON Response
NSDictionary *theJson=[yourJsonData objectForKey:#"user_name"];
for(NSMutableArray *usernames in theJson){
// do something with usernames from your object
}
My application also receives his last tweet. You should consider the limits to the server with these requests (350 per hour). If you exceed this limit, there is no nsarray in nsdata it is nsdictionary, which describes the error and the request, which will undoubtedly be taken into account. I did it this way:
NSError* error = nil;
id responseBody = [NSJSONSerialization JSONObjectWithData:data
options:NSJSONReadingMutableContainers
error:&error];
if (error) {
[[NSAlert alertWithError:error] runModal];
}
if ([responseBody respondsToSelector:#selector(objectAtIndex:)]) {
else {
if ([responseBody count]) {
NSString* currentStatus = [[responseBody objectAtIndex:0] objectForKey:#"text"]; //now you can do smth with your status))
}
else {
NSLog(#"You have not tweetted yet!");
}
}
}
else if([responseBody respondsToSelector:#selector(objectForKey:)]) {
NSString* error = [responseBody objectForKey:#"error"];
NSLog(#"CURRENT STATUS ERROR => %#", error);
}

NSURL with http:// works fine but with ftp:// not

NSString *adress = [NSString stringWithFormat:#"ftp://%#:%##%#/%#x050-pegel.txt", benutzer.text, passwort.text, server.text, pfad.text];
NSURL *aURL = [[NSURL alloc]initWithString:adress];
NSString *theData = [NSString stringWithContentsOfURL:aURL];
textview.text = theData;
can some one help me please ?
AFAIK, FTP support is not part of the Cocoa frameworks. You could get more information by using +[NSString stringWithContentsOfURL:encoding:error:] and looking at the NSError object, like so:
NSError *error = nil;
NSString *theData = [NSString stringWithContentsOfURL:aURL encoding:NSUTF8StringEncoding error:&error];
if (error != nil) {
NSLog(#"received error: %#", error);
}
A quick google search for "cocoa ftp" shows that there are several approaches to connecting to an FTP server from Objective-C.