Assigning text to UILabel gives error after parsing JSON - ios

I've the following code for receiving response from PHP web service in JSON Format:
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *responseStringWithEncoded = [[NSString alloc] initWithData: mutableData encoding:NSUTF8StringEncoding];
NSLog(#"Response from Server : %#", responseStringWithEncoded);
[self getData:responseStringWithEncoded];
}
-(void) getData:(NSString *) responseStringWithEncoded{
NSData *data = [responseStringWithEncoded dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSLog(#"object for key ime = %#", [json objectForKey:#"imei"]);
NSString * jimei = [json objectForKey:#"imei"];
NSLog(#"jimei = %#", jimei);
// NSDictionary * jimei = [json objectForKey:#"imei"];
imeiLable.text = jimei;
}
I am successfully retrieving data in simulator but when assigning one value among received string(NSDictionary) to imeiLable.text it gives following error.
Here is the output:
Request data = { URL: http://localhost/getjsonimei.php?imei=478593219801234 }
Response from Server : {"id":7,"imei":478593219801234,"mname":"Samsung Glaxy","pamount":"2000 rupees","pname":"Faizi","address":"House number 88, block 31","cnumber":11122233,"nic":"87456893"}
object for key ime = 478593219801234
jimei = 478593219801234
Here is detailed description of simulator resulting string(dictionary) and error.
2017-05-24 20:01:13.229 imiechecker[4005:61372] -[__NSCFNumber length]: unrecognized selector sent to instance 0xb01b3472adbb0923
2017-05-24 20:01:13.263 imiechecker[4005:61372] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFNumber length]: unrecognized selector sent to instance 0xb01b3472adbb0923'
I also tried following approach:
NSDictionary * jimei = [json objectForKey:#"imei"];
but having the same error.
Please suggest where I am doing it wrong?

Your IMEI number is of data type NSNumber, not NSString.
Try this:
NSString * jimei = [NSString stringWithFormat:#"%#", [json objectForKey:#"imei"]];
imeiLable.text = jimei;

Related

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (NSConcreteValue)

This is my dictionary:
{ #"RoutePolyline":<__NSArrayM 0x283983750>(<c59272f7 39263940 55a4c2d8 42f65240>),
#"RideID":6565
};
I am sending this dictionary as an argument in my API call.
and my app crashes at this line of code:
NSData *postData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
This is the error it throws:
Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: 'Invalid type in JSON write
(NSConcreteValue)'
I know the RoutePolyline parameter is holding a NSValue (it is supposed to be an array of coordinates) and not any object type, but I have tried converting alot, but nothing have worked so far. For example
[NSValue valueWithMKCoordinate:*routeCoordinates]
Loop through your NSValue array and extract CLLocationCoordinate2D's value.
for (NSValue *value in coordinates) {
CLLocationCoordinate2D coordinate;
[value getValue:&coordinate];
NSDictionary *coDic = #{#"latitude" : [NSNumber numberWithDouble: coordinate.latitude],
#"longitude": [NSNumber numberWithDouble: coordinate.longitude]};
[array addObject:coDic];
}
Also Check if dictionary is valid JSON before serialize
if ([NSJSONSerialization isValidJSONObject:dic]) {
NSData *postData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:&error];
}
Get coordinates (lat longs) values first and store to an array, you can serialize then, it should not crash. Try by using NSString values in api:
NSArray *arr = #[ #{#“lat”: [NSString stringWithFormat:#"%ld",routeCoordinates.latitude],
#“long”:[NSString stringWithFormat:#"%ld",routeCoordinates.longitude]
}];

Objective-C Json Fetch And Parse Data

I'm trying to parse data from my api.My code is correct.I used it a lot of time.But I didn't get any error like this.What I am doing wrong.Can you help me ?
-(void)getStatu {
NSURL *urlPath = [NSURL URLWithString:#"http://myurl.com/m/cc/cc_today.php"];
NSData *jsonData = [NSData dataWithContentsOfURL:urlPath];
NSError *error = nil;
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(#"%#",dataDictionary);
_ccStatus = [NSMutableArray array];
NSArray *statuArray = [dataDictionary objectEnumerator];
for (NSDictionary *statuDictionary in statuArray) {
CCStatu *status = [CCStatu statuWithTitle:[statuDictionary objectForKey:#"gelen"]];
status.cevap = [statuDictionary objectForKey:#"cevap"];
status.cort = [statuDictionary valueForKeyPath:#"cort"];
status.kayip = [statuDictionary valueForKeyPath:#"kayip"];
status.lort = [statuDictionary valueForKeyPath:#"lort"];
status.tekil = [statuDictionary valueForKey:#"tekil"];
[_ccStatus addObject:status];
}
}
This is my json
2015-08-13 23:54:41.362 CSGB[3215:209292] {
cevap = "37,627";
cort = "00:00:48";
gelen = "54,247";
kayip = "16,620";
lort = "00:01:17";
sl = "46.30 %";
tekil = "3,316";
}
And this is error
2015-08-13 23:54:58.330 APP[3215:209292] -[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x7fcc12451c30
2015-08-13 23:54:58.336 APP[3215:209292] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x7fcc12451c30'
Your code is iterating the data incorrectly. You only have a single dictionary. There's nothing to iterate.
NSDictionary *dataDictionary = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error];
NSLog(#"%#",dataDictionary);
_ccStatus = [NSMutableArray array];
CCStatus *status = [CCStatu statuWithTitle:dataDictionary[#"gelen"]];
status.cevap = dataDictionary[#"cevap"];
status.cort = dataDictionary[#"cort"];
status.kayip = dataDictionary[#"kayip"];
status.lort = dataDictionary[#"lort"];
status.tekil = dataDictionary[#"tekil"];
[_ccStatus addObject:status];

JSON Parsing in Xcode returning error

I'm trying to parse the following JSON information that comes out of my PHP file:
{
"netSales":0,
"voidSales":0,
"discountSales":0,
"guestCount":null,
"servedCount":null,
"loggedIn":9
}
My string is set something like this:
NSURL * url = [NSURL URLWithString:salesStr];
NSData * data = [NSData dataWithContentsOfURL:url];
json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(#"response type is %#",[json class]);
//Set up our cities array
arrayOfStore = [[NSMutableArray alloc]init];
for (int i = 0; i < json.count; i++)
{
NSString * netSales = json[i][#"netSales"];
NSString * voids = json[i][#"voidSales"];
NSString * discounts = json[i][#"discountSales"];
NSString * guestCount = json[i][#"guestCount"];
NSString * peopleServed = json[i][#"servedCount"];
NSString * employeesClock = json[i][#"loggedIn"];
Store * myStore = [[Store alloc]initWithNetSales: (NSString *) netSales andVoids: (NSString *) voids andDiscounts: (NSString *) discounts andGuestCount: (NSString *) guestCount andPeopleServed: (NSString *) peopleServed andEmployeesClock: (NSString *) employeesClock];
[arrayOfStore addObject:myStore];
But it's returning the error message:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x8ddb930'
What does this error mean?
EDIT: I extended my code a bit.
Your error message, "[__NSCFDictionary objectAtIndex:]: unrecognized selector sent", is informing you that you attempted to call objectAtIndex (an array method) on an object that was really a dictionary.
Your code snippet appears to assume that the JSON is an array of dictionaries. But on the basis of what you've shared with us, it looks like a simple dictionary. That is consistent with the error message you received. You could remedy this by just calling objectForKey, and eliminate the call to objectAtIndex.
By the way, netSales appears to be a number, not a string, so use NSNumber rather than NSString.
So, putting those together, I think you'd want:
NSNumber *netSales = json[#"netSales"]; // or [json objectForKey:#"netSales"];

Why does my iOS app crash with JSON?

I'm trying to acces my JSON in Objective-C from a higher scope. But it keeps crashing and I have no idea why.
The following code works:
- (void)fetchedData:(NSData *)responseData {
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONOnkectWithData: responseData
options:kNilOptions
error:&error];
NSArray* nameAndPlace = [[json objectForKey:#"objects"] objectForKey:#"havens"];
//NSArray* productArray = [[json objectForKey:#"objects"] objectForKey:#"products"];
NSLog(#"FROM ---> %#", nameAndPlace);
for (NSDictionary *mapPointLoop in nameAndPlace) {
NSString * name = [mapPointLoop objectForKey:#"name"];
NSString * longitudeGet = [mapPointLoop objectForKey:#"longitude"];
NSString * latitudeGet = [mapPointLoop objectForKey:#"latitude"];
myAnnotation *annotation1 = [[myAnnotation alloc] init];
CLLocationCoordinate2D coordinate1;
coordinate1.longitude = longitude;
coordinate1.latitude = latitude;
annotation1.coordinate = coordinate1;
annotation1.title = name;
[mainMap addAnnotation:annotation1];
//NSLog(#"FROM ---> %#", mapPointLoop);
}
}
But when I use this it crashes:
- (void)fetchedData:(NSData *)responseData {
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:responseData
options:kNilOptions
error:&error];
NSArray* nameAndPlace = [json objectForKey:#"objects"];
//NSArray* productArray = [[json objectForKey:#"objects"] objectForKey:#"products"];
NSLog(#"FROM -> %#", nameAndP1ace);
for (NSDictionary *mapPointLoop in nameAndPlace) {
NSString * name = [[mapPointLoop objectForKey:#"havens"] objectForKey:#"name"];
NSNumber * longitudeGet = [mapPointLoop objectForKey:#"longitude"];
NSNumber * latitudeGet = [mapPointLoop objectForKey:#"latitude"];
float latitude = [latitudeGet floatvalue];
float longitude = [longitudeGet floatvalue];
myAnnotation *annotation1 = [[myAnnotation alloc] init];
CLLocationCoordinate2D coordinate1;
coordinate1.longitude = longitude;
coordinate1.latitude = latitude;
annotation1.coordinate = coordinate1
annotation1.title = name;
[mainMap addAnnotation:annotation1];
//NSLog(#"FROM -> %#", mapPointLoop):
}
}
It crashes with the error...
2014-05-20 17:49:57.709 labelAPortTest[5556:60b] * Terminating app
due to uncaught exception 'NSInvalidArgumentException', reason:
'-[__NSCFString objectForKey:]: unrecognized selector sent to instance
0x1172426b0'
It crash because when you take the name:
NSString *name = [[mapPointLoop objectForKey:#"havnes"] objectForKey:#"name"];
this:
[mapPointLoop objectForKey:#"havens"]
is an NSArray and not an NSDictionary with the key name.
In fact in your first code you take the objectForKey:#"objects"] objectForKey:#"havens]"
so you have this situation:
NSDictionary ~> objects ~> NSDictionary ~> havens ~> NSArray (of NSDictionary)
then you go to through a for cycle getting 1 to 1 the NSDictionary in the NSArray.
Second case (that crash):
NSDictionary ~> objects ~> NSDictionary
but your are putting that in an NSArray going again with the for cycle..on an NSDictionary.
But it keeps crashing and I have no idea why.
The reason is right here:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFString objectForKey:]: unrecognized selector sent to instance 0x1172426b0'
You have an uncaught exception. Furthermore, you have some information about what that exception is, namely that you're sending the objectForKey: message to an object that doesn't implement it.
The first thing you should do is to set a breakpoint for all exceptions:
That'll cause the debugger to stop as soon as the exception is thrown instead of waiting until the app exits, which will give you a lot more context. You should be able to see which object is getting the unknown message. If that doesn't make the problem completely clear, set a breakpoint a line or two before the exception happens and step through the code a line at a time until you find the problem.

Get Row from NSArray

Hello i get a json that looks like this:
features: (
{
attributes = {
Gecontroleerd = Ja;
};
geometry = {
x = "5.968097965285907";
y = "52.50707112779077";
};
}
)
From this code:
NSDictionary *root = [NSJSONSerialization JSONObjectWithData:responseData options:0 error:nil];
NSArray *data = [root objectForKey:#"features"];
NSLog(#"features: %#", data );
for (NSArray *row in data) {
NSString *latitude = row[5];
NSString *longitude = row[7];
NSString *crimeDescription = #"test";
NSString *address = #"banaan";
And u need to x values 5.968097965285907 for latitude
and y values 52.50707112779077 for longitude
But i get this error:
[__NSCFDictionary objectAtIndexedSubscript:]: unrecognized selector sent to instance 0x14831450
2012-11-14 10:10:59.000 ArrestPlotter[6330:c07] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary objectAtIndexedSubscript:]: unrecognized selector sent to instance 0x14831450'
*** First throw call stack:
(0x1860012 0x1655e7e 0x18eb4bd 0x184fbbc 0x184f94e 0x2dbc 0x3b8f 0x1cc1e 0x16696b0 0xfa0035 0x17e3f3f 0x17e396f 0x1806734 0x1805f44 0x1805e1b 0x224a7e3 0x224a668 0x4a765c 0x25bd 0x24e5 0x1)
libc++abi.dylib: terminate called throwing an exception
(lldb)
Does anyone wich row i need to select?
I guess that the only thing is that the row number needs to be changed. Or maybe there should be something like this : [1][5]. Im not quite sure how this works
NSArray *data = [root objectForKey:#"features"];
NSLog(#"features: %#", data );
for (NSDictionary *dic in data) {
NSDictionary geometry = [dic objectForKey:#"geometry"];
// Do what you want..
NSString *myAwesomeX = [geometry objectForKey:#"x"];
NSString *myAwesomeY = [geometry objectForKey:#"y"];
}
The problem here is that you are trying to send a selector message to object row, that is in memory a NSDictionary (NSCFDictionary?) object, and you are trying to manage it like a NSArray.
The method objectAtIndexedSubscript (is underlying called by row[5] and row[7]) exists in NSDictionary, but no in NSArray.
Change
for (NSArray *row in data) {
by
for (NSDictionary *row in data) {
Also, you have to change the management of data inside for, look at the result of your log statement and act accord whit it.
I hope this will help!

Resources