How to solve json Error in ios 7? - iphone

Am using following code.
+(void)getQuarterList:(NSString *)user_id
{
if ([self checkInternet])
{
NSString *url=[NSString stringWithFormat:#"%#/api/v1/quarters.json",MainURL];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{#"id":user_id};
// NSDictionary *parameters = #{};
// NSDictionary *parameters = #{#"id":user_id,#"auth_token":auth_token};
[manager POST:url parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject)
{
NSDictionary *dict=[[NSDictionary alloc]initWithDictionary:responseObject];
//NSMutableArray *dict=[[NSMutableArray alloc]initWithArray:responseObject];
NSLog(#"dict%#",dict);
if ([dict valueForKey:#"Success"])
{
NSNotification *notif1 = [NSNotification notificationWithName:#"quarterDetailsNotifier" object:[dict valueForKey:#"Success"]];
[[NSNotificationCenter defaultCenter] postNotification:notif1];
}
else if ([dict valueForKey:#"noData"])
{
NSNotification *notif1 = [NSNotification notificationWithName:#"noDateNotifier" object:[dict valueForKey:#"Error"]];
[[NSNotificationCenter defaultCenter] postNotification:notif1];
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
NSNotification *notif1 = [NSNotification notificationWithName:#"quarterDetailsFailNotifier" object:error];
[[NSNotificationCenter defaultCenter] postNotification:notif1];
}];
}
else
{
NSNotification *notif1 = [NSNotification notificationWithName:#"internetFailNotifier" object:nil];
[[NSNotificationCenter defaultCenter] postNotification:notif1];
}
}
am having following error
2014-05-20 15:39:33.610 TMLP[2770:a0b] The internet is working via WIFI.
2014-05-20 15:39:35.733 TMLP[2770:a0b] Error: 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=0x8e4a1a0 {NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set., NSUnderlyingError=0x8e65ca0 "Request failed: not found (404)"}
2014-05-20 15:39:35.734 TMLP[2770:a0b] -[NSError length]: unrecognized selector sent to instance 0x8e4a180
2014-05-20 15:39:35.737 TMLP[2770:a0b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSError length]: unrecognized selector sent to instance 0x8e4a180'
* First throw call stack:
how to solve this error

You post error as an object of NSNotification. And in notifcation handler you use it as NSString or other object that has method length.

First things first.
Your obtained JSON text should always start with a "[" or "{" for the parser to recognise it. And the reason you are getting this error is clearly because this is not fulfilled.
I suggest you check your JSON text through a JSON validator which is available online.
And the Second thing I Suggest is to use for JSON Serialization/Deserialization is
NSJSONSerialization
And Example would be like this :
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingAllowFragments error: &error];
The options:NSJSONReadingAllowFragments might solve your problem of parsing fragments that you are getting right now. If this doesn't help, another option would be to extract out the proper JSON string from the obtained fragmented string.This means eliminating the extra unwanted characters from the starting and end of the string.
An Example would be like this :
NSURL *url=[NSURL URLWithString:#"yourURL"];
NSData *response = [NSData dataWithContentsOfURL:url];
NSString *badjsonData = [NSString stringWithUTF8String:[response bytes]];
NSString *goodJsonData = [badjsonData substringFromIndex:76];
NSString *finaljsonData = [goodjsonData substringToIndex:[goodjsonData length]-9];
NSData *goodData = [finaljsonData dataUsingEncoding:NSUTF8StringEncoding];
NSError *error;
NSDictionary *jsonArray = [NSJSONSerialization JSONObjectWithData:goodData options:NSJSONReadingAllowFragments error: &error];

Related

NSError strange issue - app crashes while trying to access NSError's properties

In the following code NSError instantiates (match is GameCenter's GKMatch):
...
NSString * deviceID = appDelegate.deviceID;
MessageWithDeviceID message;
message.message.messageType = kMessageTypeDeviceID;
const char* const deviceIDAsUTF8 = deviceID.UTF8String;
for (size_t idx=0;idx<32;idx++)
message.deviceID[idx] = deviceIDAsUTF8[idx];
NSData *data = [NSData dataWithBytes:&message length:sizeof(message)];
NSError * error;
[match sendDataToAllPlayers:data withDataMode:GKMatchSendDataReliable error:&error];
data = nil;
if (error)
NSLog(#"An error is occured: %#",error);
...
but the app crashes at the last shown line with EXC_BAD_ACCESS or SIGABRT -[NSCFString userInfo (or domain, localizedDescription, code etc)] unrecognized selector sent to instance 0x.... So I can see that error is not nil and it is instantiated object but I can't get any information from it. I tried to get the following:
[error localizedDescription];
[error domain];
[error code];
[error description];
etc.
but app still crashes at NSLog line no matter which info I'm trying to get. I know the approach isn't right and I need to use BOOL variable in line which sends data but thats not the point of question. The question is whats wrong with the NSError object? I could see error's fields in debugger (those expandable info) like:
NSObject NSObject
void * _reserved
NSInteger _code 875902004 Summary
NSString * _domain
NSDictionary * _userInfo
So it seems like error object does have all the info but its unaccessible... Why is it so? Is NSError somehow not fully/completely instantiated or something?
Try initializing your error pointer to nil
NSError * error = nil;
You get a crash because there was no error and your pointer contains a random address.
Replace this line.
NSError* error = nil;

displaying JSON data with the help of dictionaries and array

I get the following error
[__NSCFDictionary objectAtIndex:]: unrecognized selector sent to instance 0x75a8e20
2013-04-20 08:56:14.90 MyApp[407:c07] *** Terminating app due to uncaught
exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary objectAtIndex:]:
unrecognized selector sent to instance 0x75a8e20'
This is my first hands on working with JSON. I get the above mentioned error when I try to run the first piece of code where URL is a flickr url. When I use the photos as key it print the array and app abruptly quits.
#define flickrPhotoURL [NSURL URLWithString: #"http://api.flickr.com/services/rest/?format=json&sort=random&method=flickr.photos.search&tags=rocket&tag_mode=all&api_key=12345&nojsoncallback=1"]
- (void)viewDidLoad
{
[super viewDidLoad];
//this line of code will be executed in the background to download the contents of the flickr URL
dispatch_async(flickrBgQueue, ^{
NSData* flickrData = [NSData dataWithContentsOfURL:flickrPhotoURL]; //NOTE: synchronous method...But we actually need to implement asynchronous method
[self performSelectorOnMainThread:#selector(appFetchedData:) withObject:flickrData waitUntilDone:YES]; //when data is available "appFetchedData" method will be called
});
}
- (void)appFetchedData: (NSData *)responseData
{
//parsing JSON data
NSError *error_parsing;
NSDictionary *flickr_json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error_parsing];
NSArray* photo_information = [flickr_json objectForKey:#"photos"];
NSLog(#"Photo Information: %#",photo_information);
NSDictionary* photo = (NSDictionary*)[photo_information objectAtIndex:0];
humanReadable.text = [NSString stringWithFormat:#"Owner is %#",[photo objectForKey:#"Owner"]];
}
However when I run the same piece of code by replacing the key "photos" with "loans" and use the following URL and code
#define flickrPhotoURL [NSURL URLWithString: #"http://api.kivaws.org/v1/loans/search.json?status=fundraising"]
- (void)appFetchedData: (NSData *)responseData
{
//parsing JSON data
NSError *error_parsing;
NSDictionary *flickr_json = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error_parsing];
NSArray* photo_information = [flickr_json objectForKey:#"loans"];
NSLog(#"Photo Information: %#",photo_information);
NSDictionary* photo = (NSDictionary*)[photo_information objectAtIndex:0];
humanReadable.text = [NSString stringWithFormat:#"loan amount is %#",[photo objectForKey:#"loan_amount"]];
}
, the app sets the correct information on the humanredable.text property. Am I using the wrong key for the first JSON ?
Firstly, thanks for publishing your Flickr API key as-is! It will be super useful for me to perform identity theft some day.
Second, another big thanks for not having read the data you got back. It starts like this:
{"photos":{"page":1, "pages":1792, "perpage":100,
^^^^^^^^^^
So the object for the key photos is a dictionary, not an array, thus,
NSArray* photo_information = [flickr_json objectForKey:#"photos"];
is wrong. Did you mean this instead:
NSArray* photo_information = [[flickr_json objectForKey:#"photos"]
objectForKey:#"photo"];
? Also, below when you construct the human readable description,
[photo objectForKey:#"Owner"]
is wrong, it should be
[photo objectForKey:#"owner"]
instead.

Getting isEqualToString: unrecognized selector sent to instance error

I'm getting this error when clicking the same UIButton twice, it crashes the second time only when the request to the server is not able to go through.
-[SendHelloFax isEqualToString:]: unrecognized selector sent to instance 0x12b49150
Update: I used breakpoints and found that the line it is crashing at is:
if (!errorMessage || [errorMessage isEqualToString:#""])
{
errorMessage = #"Failed to send fax. Please check your WiFi or 3G connection and try again.";
}
Methods:
- (IBAction)sendFaxButtonClicked:(id)sender
{
NSString *errorMessage;
int rcode = [MyDataSource sendFax:self.appointment phone_call_id:self.phone_call_id document_url:self.document_url targetId:self.contact_id targetName:self.name.text targetNumber:self.faxNumber.text coverSheetMessage:self.coverSheetMessage.text errorMessage:&errorMessage];
if (rcode) {
if (!errorMessage || [errorMessage isEqualToString:#""]) {
errorMessage = #"Failed to send fax. Please check your WiFi or 3G connection and try again.";
}
UIAlertView *someError = [[UIAlertView alloc] initWithTitle: #"Error" message:errorMessage delegate: self cancelButtonTitle: #"Ok" otherButtonTitles: nil];
[someError show];
[someError release];
return;
}
if (!rcode) {
[self dismissModalViewControllerAnimated:FALSE];
}
}
+(int)sendFax:(int)appointment_id phone_call_id:(int)phone_call_id document_url:(NSString*)document_url targetId:(int)contactId targetName:(NSString*)targetName targetNumber:(NSString*)targetNumber coverSheetMessage:(NSString*)coverSheetMessage errorMessage:(NSString**)errorMessage
{
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#/ichrono/20110715/60b88126/fax_send/", [self getMyHost]]];
ASIFormDataRequest *request = [[[ASIFormDataRequest alloc] initWithURL:url] autorelease];
[self addCurrentUserLoginToPostRequest:request];
[request setPostValue:[NSString stringWithFormat:#"%d", contactId] forKey:#"fax_contact_id"];
[request setPostValue:[NSString stringWithFormat:#"%d", appointment_id] forKey:#"appointment_id"];
[request setPostValue:[NSString stringWithFormat:#"%d", phone_call_id] forKey:#"phone_call_id"];
[request setPostValue:document_url forKey:#"url_to_fax"];
[request setPostValue:targetNumber forKey:#"fax_number"];
[request setPostValue:targetName forKey:#"full_name"];
[request setPostValue:coverSheetMessage forKey:#"coversheet_message"];
[request startSynchronous];
NSError *error = [request error];
NSString *responseString;
if (!error) {
responseString = [request responseString];
} else {
return -1;
}
NSMutableDictionary *temp = [responseString JSONValue];
*errorMessage = [temp valueForKey:#"errors"];
if ([[temp valueForKey:#"status"] isEqualToString:#"ok"]) {
return 0;
} else {
return -1;
}
}
Best bet is that errorMessage is not initialized and not set to a NSString even though rcode is not 0.
Try: NSString *errorMessage - nil; and checking to insure errorMessage is set in this instance.
When, at the beginning of your method, you define - without initialization -:
NSString *errorMessage;
you're in fact defining an id which has not been set to a valid value (that is a valid string using alloc-init or simply nil) so the memory area content pointed by errorMessage is not valid, that is it can be anything: an invalid area (which will lead to EXC_BAD_ACCESS) or another area previously taken by a now dealloc'd class (like in your case: this will raise an invalid selector exception) or in the worst case an area taken by another now dealloc'd NSString (difficult to debug!).
Later you call sendFax:phone_call_id:... method which returns rcode and has as side effect to update the errorMessage pointer by let it point to a valid address (or nil). It doesn't and then when you check errorMessage you get one of the errors above.
I suppose from your code that when rcode is set some error occurred. In such case this method must assign something to errorMessage, even a nil or an empty string, to avoid this error. So probably the sendFax: method is missing this detail.

using XMLRPC with iphone giving error (please go in detail for more)?

Error I am getting:
*[NSURLError object]: unrecognized selector sent to instance 0x5f510e0 *
2010-10-11 11:41:33.718 CBH[15454:207] ** Terminating app due to uncaught exception *'NSInvalidArgumentException', reason: '-[NSURLError object]: unrecognized selector sent to instance 0x5f510e0' *
here is the code:
NSArray *args = [NSArray arrayWithObjects:#"username",#"password",nil]; // the param(s)
NSString *server = #"https://username:password#webservices.****.***:443/dsa/xmlrpc/restricted1/"; // the server
XMLRPCRequest *request = [[XMLRPCRequest alloc] initWithHost:[NSURL URLWithString:server]];
[request setMethod:#"BootService.getPublicTokenGeneric" withObject:args];
id response = [self executeXMLRPCRequest:request];
[request release];
if( [response isKindOfClass:[NSError class]] ) {
NSLog(#"Error : %#",response);
}
else {
NSLog(#"Response ");
}
}
- (id)executeXMLRPCRequest:(XMLRPCRequest *)req {
NSLog(#"HEllo");
XMLRPCResponse *userInfoResponse = [XMLRPCConnection sendSynchronousXMLRPCRequest:req];
if([userInfoResponse isKindOfClass:[NSError class]]) {
NSLog(#"Error %#",userInfoResponse);
}
return [userInfoResponse object];
}
Could some one help me tearing out this error!!
I edited the code and now I can see NSURLError is:
Domain=NSURLErrorDomain Code=-1005 "The network connection was lost."
NSErrorFailingURLStringKey=http://username:password#..org:443/zws/xmlrpc/restricted1/, NSErrorFailingURLKey=http://username:password#..org:443/zws/xmlrpc/restricted1/,
NSLocalizedDescription=The network connection was lost., NSUnderlyingError=0x5f2b300 "The network connection was lost.
Looks like XMLRPCConnection is giving you back an NSURLError object which does not like the object selector you are calling.
So userInfoResponse IS an NSURLError. You will need to test for this just like you are testing for NSError, although sooner.
XMLRPCResponse *userInfoResponse = [XMLRPCConnection sendSynchronousXMLRPCRequest:req];
if([userInfoResponse isKindOfClass:[NSURLError class]]) {
//Do something else
}
else return [userInfoResponse object];
Your id based code is prone to these kind of errors, I suggest more strongly typed methods.

-[NSPathStore2 objectForKey:]: unrecognized selector sent to instance 0x6a3fc60'

I was preparing for a customCellView in a tableView. According to me, everything was perfect in .xib and methods. I am getting an exception in configuring the cell.
int listIndex = [indexPath indexAtPosition:[indexPath length] - 1];
NSLog(#"outside");
cell.lblName.text = (NSString *) [[directoryContent objectAtIndex:listIndex] objectForKey:#"filesName"];
cell.lblSize.text = (NSString *) [[directoryContent objectAtIndex:listIndex] objectForKey:#"filesSize"];
cell.lblType.text = (NSString *) [[directoryContent objectAtIndex:listIndex] objectForKey:#"filesType"];
return cell;
The compiler works till the NSLog(#"outside");. But it does not proceeds to the next line. I am terminated by the error
2010-11-15 20:32:28.623 iDataTraveller[5346:207] outside
2010-11-15 20:32:28.625 iDataTraveller[5346:207] -[NSPathStore2 objectForKey:]: unrecognized selector sent to instance 0x5f19cf0
2010-11-15 20:32:28.627 iDataTraveller[5346:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[NSPathStore2 objectForKey:]: unrecognized selector sent to instance 0x5f19cf0'
Please help me to proceed.. Thank you in advance..
Wherever you created directoryContent, you stored the wrong object in it.
NSPathStore2 is an object that will be created if you use something like stringByAppendingPathComponent: on a NSString.
I guess you just stored the filename in the array but wanted to store a NSDictionary created from NSFileManagers attributesOfItemAtPath:error:
Check that part were you add objects to directoryContent again.
This is my code. Have a look at this. Let me know what i am lagging.
- (void)listFiles {
NSFileManager *fm =[NSFileManager defaultManager];
NSError *error = nil;
NSString *parentDirectory = #"/Users/akilan/Documents";
NSArray *paths = [fm contentsOfDirectoryAtPath:parentDirectory error:&error];
if (error) {
NSLog(#"%#", [error localizedDescription]);
error = nil;
}
NSMutableArray *array = [[NSMutableArray alloc] init];
self.directoryContent = array;
[array release];
for (NSString *path in paths){
filesName = [[path lastPathComponent] stringByDeletingPathExtension];
filesPath = [parentDirectory stringByAppendingPathComponent:path];
filesDirectory = [NSMutableDictionary dictionaryWithDictionary:[[NSFileManager defaultManager] attributesOfItemAtPath:filesPath error:nil]];
filesSize = [filesDirectory objectForKey:NSFileSize];
filesType = [path pathExtension];
createdDate = [filesDirectory objectForKey:NSFileCreationDate];
modifiedDate = [filesDirectory objectForKey:NSFileModificationDate];
filesDirectory = [NSDictionary dictionaryWithObjectsAndKeys:filesPath,#"filesPath",
filesName,#"filesName",filesSize, #"filesSize", filesType, #"filesType",
createdDate,#"createdDate", modifiedDate,#"modifiedDate", nil];
NSLog(#"%#", filesDirectory);
}
}
Thanks..
You have not retained directoryContent.
Can you show the code where directoryContent is created?
You can tell this because your error message says NSPathStore2 when it should be trying to call objectforKey on NSDictionary - this means that the memory where your dictionary was is not being used by something else :)