Parse JSON with iOS 6 and xCode 4.5.2 - objective-c

I'm new in objective-c and and building a sign in page for a specific website. When the user provide information the following JSON return back from the server:
{
"object":{},
"resultCode":0,
"resultMessage":"You successfully signed in "
}
And this what I'm trying to do based on a tutorial I found:
-(IBAction)login{
// Download JSON
NSData *data = [NSData dataWithContentsOfURL: [NSURL URLWithString:[NSString stringWithFormat:#"https://www.example.com/login?username=%#&password=%#", nationalID.text,passowrd.text]]];
NSError *error;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSArray *response = [json objectForKey:#"resultMessage"];
NSLog(#"response %#",response);
}
I want to log out "resultMessage" but somehow it throws an exception:
2012-12-13 06:46:50.607 myProject[7178:11303] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil'
*** First throw call stack:
(0x1c8d012 0x10cae7e 0x1c8cdeb 0xbff817 0x2f1a 0x10de705 0x15920 0x158b8 0xd6671 0xd6bcf 0xd5d38 0x4533f 0x45552 0x233aa 0x14cf8 0x1be8df9 0x1be8ad0 0x1c02bf5 0x1c02962 0x1c33bb6 0x1c32f44 0x1c32e1b 0x1be77e3 0x1be7668 0x1265c 0x279d 0x26c5)
libc++abi.dylib: terminate called throwing an exception

Looks like the -dataWithContentsOfURL: message failed and returned nil, which is exactly what the error message says. You need to confirm that your -stringWithFormat: message is giving you the correct URL format, and check whether the server is returning what you expect.

if you could observe the issue description:
'NSInvalidArgumentException', reason: 'data parameter is nil'
means the response from your response from the web url is nil or NULL
this is not a issue related to JSON parser.

Looks like you have a simple typo, you are using:
nationalID.text,passowrd.text
You probably meant to not misspell 'password'.

First Try static url like:
https://www.example.com/login?username=admin&password=123
if this returns you correct response then try Property Variables like:
https://www.example.com/login?username=self.username.text&password=self.password.text
And one mistake you have made is that resultMessage is string not an Array.
Hope this helps you

Related

+[NSData bookmarkDataWithContentsOfURL:]: unrecognized selector sent to class

I am trying to resolve an alias file's original path using Objective-C(or maybe C++; it's an .mm file). Not being very much familiar, I am somehow missing + and - methods' usage. I am aware of them being class and instance methods respectively, but in practice, the following the code, with the indicated lines give me following warning and error(at build):
Class method '+bookmarkDataWithContentsOfURL:' not found (return type defaults to 'id')
-
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[NSData bookmarkDataWithContentsOfURL:]: unrecognized selector sent to class 0x7fff88942cb8'
with 0x7fff88942cb8 being the NSData address as per lldb.
Which files should I make the changes in, to get bookmarkDataWithContentsOfURL:error: and URLByResolvingBookmarkData to work?
void *pathclass::resolveAliasFromURL(const char *filepath) const
{
NSError *error = nil;
NSString *filepathh = [[NSString alloc] initWithUTF8String:filepath];
NSData *bookmarkk = [NSData bookmarkDataWithContentsOfURL:filepathh]; /*problematic line*/
BOOL isstale = NO;
NSURL *actual = [NSURL URLByResolvingBookmarkData:bookmarkk bookmarkDataIsStale:isstale error:error];/*another problematic line, but build fails already*/
NSString *urlString = [actual absoluteString];
NSLog(#"%#",urlString);
}
If there are any other faults, please point out.
Your call to bookmarkDataWithContentsOfURL: is wrong in a few ways:
The signature looks like this:
+ (NSData *)bookmarkDataWithContentsOfURL:(NSURL *)bookmarkFileURL error:(NSError * _Nullable *)error;
First, the first parameter is of type NSURL*, not NSString*. Next, you miss off the error parameter completely (despite defining a variable for it). Lastly, the method is a class method on NSURL not NSData (NSData* is the return type).
So, first, make your file path into an NSURL*:
NSURL* bookmarkUrl = [NSURL URLWithString:filepathh];
Then, call the function using the proper arguments:
NSData *bookmarkk = [NSURL bookmarkDataWithContentsOfURL:bookmarkUrl error:&error];
You should check the returned value against nil - if it's nil, then an error occurred, and the error information will be contained inside error.
The documentation is quite helpful.
Your call to URLByResolvingBookmarkData:options:relativeToURL:bookmarkDataIsStale:error: has similar problems: you are missing several parameters, the first parameter should be NSURL, etc. Again, the documentation should help.

Parsing JSON data to an array

I get the following error whenI launch my app
*** Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: '- [COViewController fetchAppNetData]: unrecognized selector
sent to instance 0x716d200'
Basically I am unable to find out how to parse the JSON data to my array. The structure of my JSON is as follows
{
"meta": {},
"data": []
}
I know that meta is a dictionary and data is an array. But when I try to use the following piece of code I get the above error
- (void)fetchAppNetData:(NSData *)responseData
{
//parse JSON data
NSError *error;
NSDictionary* appNet_json = [NSJSONSerialization
JSONObjectWithData:responseData options:kNilOptions error:&error];
NSArray* appNetTimeline = [[appNet_json objectForKey:#"meta"]
objectForKey:#"data"];
NSLog(#"AppNet Timeline : %#",appNetTimeline);
}
How do I make sure that I can identify the structure of JSON properly next time, so that I can avoid this sort of issue? I am extremely sorry to come up with such kind of doubts
The error has nothing to do with the content of the method -fetchAppNetData:. That method is not even getting called.
The error is saying that you tried to invoke a method of that name on an object that doesn't respond to it. You've sent that message to an instance of class COViewController, but that's evidently not the class that implemented the method you posted.

Restkit route error

I am trying to do a simple post for a login screen. I post an email address and password. This gives me a JSON back with status-codes. If this code is 200 it also contains a person object. If it is something else it contains an error object.
I have this code for posting.
RKObjectManager *manager = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:#"http://******.com.be/nl/webservice/company-user/login/apikey/key**"]];
NSDictionary *dictionary = #{ #"email": _txtLogin.text, #"pwd": _txtPass.text};
NSMutableURLRequest *request = [manager requestWithObject:nil method:RKRequestMethodPOST path:nil parameters:dictionary];
RKObjectRequestOperation *operation = [manager objectRequestOperationWithRequest:request success:^(RKObjectRequestOperation *operation, RKMappingResult *result) {
NSLog(#"Loading mapping result: %#", result);
}
failure:nil];
[operation start];
But this code is causing the following error.
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid parameter not satisfying: route'
*** First throw call stack:
Could anybody help me? I'm new to restkit.
Kind regards
You're trying to post an object using automatic routing, however, your object is nil. Therefore, it will rely on the path parameter to work out where to POST to. This is also nil.
You need to create the object manager with a common base URL, eg. http://******.com.be/nl/webservice/company-user and supply your method with the path parameter /login/apikey/key**

how to solve run time error of [NSURL fileURLWithPath:error:]: unrecognized selector sent to class?

I am beginner in IPhone Developing. I want play sound. so, that's why I have apply this code
(void)viewDidLoad
{
NSError* err;
path=[[NSBundle mainBundle] pathForResource:#"Animalfile" ofType:#"plist"];
dict=[NSDictionary dictionaryWithContentsOfFile:path];
NSArray *animalaudio=[dict valueForKey:#"audio"];
NSString *audiolist=[animalaudio objectAtIndex:currentsound];
AVAudioPlayer *audio=[[AVAudioPlayer alloc]initWithContentsOfURL:[NSURL fileURLWithPath:audiolist error:&err]];
audio.delegate=self;
[audio play];
}
and I have got the run time error of
[NSURL fileURLWithPath:error:]: unrecognized selector sent to class 0x182121c
2012-07-14 14:51:21.711 plistdemo[1236:10703] *** Terminating app due to uncaught
exception 'NSInvalidArgumentException', reason: '+[NSURL fileURLWithPath:error:]:
unrecognized selector sent to class 0x182121c'
terminate called throwing an exceptionsharedlibrary apply-load-rules all
so, give any suggestion and source code which apply in my code
current documentation for NSURL doesn't list any such method like 'fileURLWithPath:error:'... seems like its either deprecated or incorrect.
instead try using something like:
[NSURL fileURLWithPath:audioList]
hope it helps...

Formatting NSURL

In my app, I need to make a json request to google direction service through NSURL.
I'm able to get JSON response, when the URL is static.
NSURL *googleMapsURL=[NSURL URLWithString:#"http://maps.googleapis.com/maps/api/directions/json?origin=SanFrancisco,CA&destination=Dallas,TX&waypoints=Los+Angeles,CA%7CHouston,TX&mode=driving&sensor=false"];
NSData *data=[NSData dataWithContentsOfURL:googleMapsURL];
But, when I specify the source and destination stations dynamically, it's not working.
NSString *urlString=[NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/directions/json?origin=%#&destination=%#&waypoints=Los+Angeles,CA%7CHouston,TX&mode=driving&sensor=false",sourceStation, destinationStation];
NSURL *googleMapsURL=[NSURL URLWithString:urlString];
NSData *data=[NSData dataWithContentsOfURL:googleMapsURL];
It's generating the following error.
2012-05-08 03:30:15.960 SupplyTrackerApp2[3079:16403] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'data parameter is nil'
*** First throw call stack:
(0x19a7052 0x2448d0a 0x194fa78 0x194f9e9 0xecdfbd 0x2aae6 0x2a900 0x56ffbf 0x57021b 0x5704c3 0x580b71 0x5813df 0x581986 0x5815a4 0x34650 0x19a8ec9 0x4ab5c2 0x4ab55a 0x550b76 0x55103f 0x5502fe 0x4d0a30 0x4d0c56 0x4b7384 0x4aaaa9 0x1bbefa9 0x197b1c5 0x18e0022 0x18de90a 0x18dddb4 0x18ddccb 0x1bbd879 0x1bbd93e 0x4a8a9b 0x25cd 0x2535 0x1)
terminate called throwing an exception
Can any one help me?
To me it looks like either sourceStation or destinationStation is nil. For debugging you could try setting them explicitly in the lines before your NSString *urlString definition.
NSString *sourceStation = #"SanFrancisco,CA";
NSString *destinationStation = #"Dallas,TX";
If this works, then it's a problem with filling the respective NSStrings...