'NSInvalidArgumentException', reason: '-[SBJsonParser objectWithString:error:]: unrecognized selector sent to instance 0x6695330' - iphone

While creating a login view on my iphone app, I ran into this error:
'NSInvalidArgumentException', reason: '-[SBJsonParser objectWithString:error:]:
unrecognized selector sent to instance 0x6695330'
It's coming from this line:
NSDictionary *results = [parser objectWithString:json_string error:nil];
From this method:
+ (BOOL)loginWithUsername:(NSString *)username password:(NSString *)password
{
NSString *urlString = [NSString stringWithFormat:#"%#login3", ROSE_ROOT_URL];
NSURL *url = [NSURL URLWithString:urlString];
NSString *requestString = [NSString stringWithFormat:#"&mobile=1&username=%#&password=%#", username, password];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[NSData dataWithBytes:[requestString UTF8String] length:[requestString length]]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
[request release];
// parse the JSON response into an object
// Here we're using NSArray since we're parsing an array of JSON product objects
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSDictionary *results = [parser objectWithString:json_string error:nil];
[json_string release];
[parser release];
// NSDictionary *results = [RoseFetcher fetch:request];
// [request release];
if ([[results objectForKey:#"password"] intValue] == 0)
return NO;
return YES;
}
Any help or explanation would be greatly appreciated.

According to the documentation for SBJsonParser, it doesn't have a method called -objectWithString:error: - an opinion that's corroborated by your findings at runtime. Try sending it a message it will respond to, like -objectWithString:.

Related

how to call webservice in xcode by GET Method?

I have this link :
function new_message($chat_id,$user_id,$message,$recipient_ids)
http://www.demii.com/demo/dooponz/admin/index.php/chat/new_message/4/1/you/2%2C7
return chat_log_id
Can anyone please explain me how to call webserive by this get method or give me the
solution .
what i did with my code is below :
-(void)newMessage{
if ([self connectedToWiFi]){
NSString *urlString = [NSString stringWithFormat:#"www.demii.com/demo/dooponz/admin/index.php/chat/new_message/4/1/you/1,1,2"];
NSLog(#"urlString is %#", urlString);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSURL *requestURL = [NSURL URLWithString:urlString];
[request setURL:requestURL];
[request setHTTPMethod:#"POST"];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSLog(#"ERROR = %#",error.localizedDescription);
if(error.localizedDescription == NULL)
{
NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"response >>>>>>>>> succ %#",returnString);
[delegate ConnectionDidFinishLoading:returnString : #"newMessage"];
}
else
{
NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"response >>>>>>>>> fail %#",returnString);
[delegate ConnectiondidFailWithError:returnString : #"newMessage"];
}
}];
}
}
how can i handle this ?
Thanks in advance .
I am not sure from your post whether or not you want to "post" or "get." However, gauging from the fact that you set your method to post, and that you are creating something new on your server, I am assuming you want to post.
If you want to post you can use my wrapper method for a post request.
+ (NSData *) myPostRequest: (NSString *) requestString withURL: (NSURL *) url{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:#"POST"];
[request setTimeoutInterval:15.0];
NSData *requestBody = [requestString dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
[request setHTTPBody:requestBody];
NSURLResponse *response = NULL;
NSError *requestError = NULL;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
return responseData;
}
Where request string is formatted like this:
NSString * requestString = [[NSString alloc] initWithFormat:#"username=%#&password=%#", userInfo[#"username"], userInfo[#"password"]];
This will also shoot back the response data which you can turn into a string like this.
responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
If you are trying to grab data from the server in json format...
+ (NSArray *) myGetRequest: (NSURL *) url{
NSArray *json = [[NSArray alloc] init];
NSData* data = [NSData dataWithContentsOfURL:
url];
NSError *error;
if (data)
json = [[NSArray alloc] initWithArray:[NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&error]];
//NSLog(#"get results: \n %#", json);
return json;
}
Pls change ur code like this
-(void)newMessage{
NSString *urlString = [NSString stringWithFormat:#"http://www.demii.com/demo/dooponz/admin/index.php/chat/new_message/4/1/you/27" ];
NSLog(#"urlString is %#", urlString);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSURL *requestURL = [NSURL URLWithString:urlString];
[request setURL:requestURL];
[request setHTTPMethod:#"POST"];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
NSLog(#"ERROR = %#",error.localizedDescription);
if(error.localizedDescription == NULL)
{
NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"response >>>>>>>>> succ %#",returnString);
[self parseStringtoJSON:data];
//[delegate ConnectionDidFinishLoading:returnString : #"newMessage"];
}
else
{
NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"response >>>>>>>>> fail %#",returnString);
// [delegate ConnectiondidFailWithError:returnString : #"newMessage"];
}
}];
}
-(void)parseStringtoJSON:(NSData *)data{
NSDictionary *dict=[NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];
NSLog(#"chat id %#",[dict objectForKey:#"chat_log_id"]);
}
u will get the JSON response string as result if u hit that url. If u r familiar with json parsing, u can get the value based on key.
see this link: How do I deserialize a JSON string into an NSDictionary? (For iOS 5+)

passing parameters in wcf using iphone

I am passing some parameters to wcf service to get the data, every thing running fine but i am not getting the data. i want to check how the parameters are calling the service and debug it. can any one let me know how to check it.
please find my code below for your reference.
NSArray *propertyNames = [NSArray arrayWithObjects:#"studentID", nil];
NSArray *propertyValues = [NSArray arrayWithObjects:#"E6A83233-7D7F-49AF-B54E-375BBF3E3E59", nil];
NSDictionary *properties = [NSDictionary dictionaryWithObjects:propertyValues forKeys:propertyNames];
// NSMutableDictionary* personObject = [NSMutableDictionary dictionary];
// [personObject setObject:properties forKey:#"person"];
NSMutableArray * arr;
//[arr addObject: personObject];
arr=[[NSMutableArray alloc]initWithObjects:properties, nil];
NSLog(#"%#",arr);
// NSString *jsonString = [personObject JSONRepresentation];
//NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
NSError * error;
NSData *jsonData2 = [NSJSONSerialization dataWithJSONObject:arr options:NSJSONWritingPrettyPrinted error:&error];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://parentportal.technologyorg.com/parentportal.svc/GetSchoolEvents"]];
NSString *jsonString = [[NSString alloc] initWithData:jsonData2 encoding:NSUTF8StringEncoding];
[request setValue:jsonString forHTTPHeaderField:#"json"];
[request setHTTPMethod:#"Post"];
[request setHTTPBody:jsonData2];
NSLog(#"JSON String: %#",jsonString);
NSError *errorReturned = nil;
NSURLResponse *theResponse =[[NSURLResponse alloc]init];
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&theResponse error:&errorReturned];
if (errorReturned) {
//...handle the error
NSLog(#"error");
}
else {
NSString *retVal = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
//...do something with the returned value
NSLog(#"RETVAL%#",retVal);
}
let me know if any thing went wrong

URL Decoding of json in ios

I am having 1 webservice in php which is having browser url mentioned bel :
http:Domain/webservice/ACTEC_WebService.php?lastupdate=2012-09-01 01:00:00
Now when I try to fetch url in my iphone app, it is taking this url:
http://Domain/webservice/ACTEC_WebService.php?lastupdate=2012-09-01%2001:00:00
This is creating problem.
i have used this code for fetching data from my url.
SBJSON *json = [SBJSON new];
json.humanReadable = YES;
responseData = [[NSMutableData data] retain];
NSString *service = #"";
NSString *str;
str = #"LastUpdated";
NSString *requestString = [NSString stringWithFormat:#"{\"LastUpdated\":\"%#\"}",str];
// [[NSUserDefaults standardUserDefaults] setValue:nil forKey:#"WRONGANSWER"];
NSLog(#"request string:%#",requestString);
NSData *requestData = [NSData dataWithBytes: [requestString UTF8String] length: [requestString length]];
NSString *fileLoc = [[NSBundle mainBundle] pathForResource:#"URLName" ofType:#"plist"];
NSDictionary *fileContents = [[NSDictionary alloc] initWithContentsOfFile:fileLoc];
NSString *urlLoc = [fileContents objectForKey:#"URL"];
//urlLoc = [urlLoc stringByAppendingString:service];
NSLog(#"URL : %#",urlLoc);
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:
[NSURL URLWithString:urlLoc]];
NSString *postLength = [NSString stringWithFormat:#"%d", [requestData length]];
[request setHTTPMethod: #"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:requestData];
NSError *respError = nil;
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: &respError ];
NSString *responseString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSLog(#"Resp : %#",responseString);
if (respError)
{
// NSString *msg = [NSString stringWithFormat:#"Connection failed! Error - %# %#",
// [respError localizedDescription],
// [[respError userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]];
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"ACTEC"
message:#"check your network connection" delegate:self cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
[alertView release];
}
else
{
......
}
here,i am getting null response as url is getting decoded...How can I make this solved...
Help me out.
Thanks in advance.
NSString *urlLoc = [[fileContents objectForKey:#"URL"] stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableData *postData = [NSMutableData data];
NSMutableURLRequest *urlRequest;
[postData appendData: [[NSString stringWithFormat: #"add your data which you want to send"] dataUsingEncoding: NSUTF8StringEncoding]];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
urlRequest = [[NSMutableURLRequest alloc] init];
[urlRequest setURL:[NSURL URLWithString:urlLoc]];
[urlRequest setHTTPMethod:#"POST"];
[urlRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[urlRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[urlRequest setHTTPBody:postData];
NSString *temp = [[NSString alloc] initWithData:postData encoding:NSUTF8StringEncoding];
NSLog(#"\n\nurl =%# \n posted data =>%#",urlLoc, temp);
check nslog. that which data u send to service.
NSData *response = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(#"json_string >> %#",json_string);
Maybe this will help you.
hey dear just for an another example i just post my this code..
first Create new SBJSON parser object
SBJSON *parser = [[SBJSON alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:
    [NSURL URLWithString:#"http:Domain/webservice/ACTEC_WebService.php?lastupdate=2012-09-01%2001:00:00"]];
Perform request and get JSON back as a NSData object
NSData *response = [NSURLConnection sendSynchronousRequest:request
    returningResponse:nil error:nil];
Get JSON as a NSString from NSData response
NSString *json_string = [[NSString alloc]
    initWithData:response encoding:NSUTF8StringEncoding];
Parse the JSON response into an object Here we're using NSArray since we're parsing an array of JSON status objects
NSArray *statuses = [parser objectWithString:json_string error:nil]
And in statuses array you have all the data you need.
i hope this help you...
:)

Not getting json response in google query of longitude and latitude in iOS?

I am new to iOS, so if any help it will be appreciated.
I am trying to get the longitude and latitude from address, earlier the code was working fine but now the JSON data are coming null.
Here my sample code,
url = [NSString stringWithFormat:#"http://maps.google.com/maps/api/geocode/json?address=%#&sensor=false",appDelegate.sAddress];
url=[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"Address URL: %#",url);
//Formulate the string as a URL object.
NSURL *requestURL=[NSURL URLWithString:url];
NSData* data = [NSData dataWithContentsOfURL: requestURL];
NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"my Coordinate : %#",returnString);
NSError* error;
NSDictionary* json = [NSJSONSerialization
JSONObjectWithData:data
options:kNilOptions
error:&error];
But i am getting the output as null.
So please help me out.
Thanks!
Thanks for your replies that all make me learn a lots.
As one of my friend just tell me the solution so i am sharing with you.
Here is the code,
url = [NSString stringWithFormat:#"http://maps.google.com/maps/api/geocode/json?address=%#&sensor=false",appDelegate.sAddress];
url=[url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSLog(#"Address URL: %#",url);
//Formulate the string as a URL object.
NSURL *requestURL=[NSURL URLWithString:url];
NSData* data = [NSData dataWithContentsOfURL: requestURL];
NSString *returnString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
SBJSON *parser = [[SBJSON alloc] init];
NSDictionary *locationResult = [parser objectWithString:returnString];
//[reverseGeoString copy]`
And its working fine.
But still there is a question that why this happen.As earlier that code is working fine but it suddenly stopped working.
You must construct your returnString in the following method that actually receives the data:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
Check out this for additional information on how to use NSURLConnection and the delegate methods.
I would say you're missing the all-important "REQUEST"...
This is what I do. Hope it helps:
NSString *encodedAddress = (__bridge_transfer NSString *) CFURLCreateStringByAddingPercentEscapes(NULL, (__bridge_retained CFStringRef)searchBar.text, NULL, (CFStringRef) #"!*'();:#&=+$,/?%#[]",kCFStringEncodingUTF8 );
NSString* searchURL = [NSString stringWithFormat:#"http://maps.googleapis.com/maps/api/geocode/json?address=%#&sensor=true",encodedAddress];
NSError* error = nil;
NSURLResponse* response = nil;
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] init];
NSURL* URL = [NSURL URLWithString:searchURL];
[request setURL:URL];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setTimeoutInterval:30];
NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error){
NSLog(#"Error performing request %#", searchURL);
return;
}
NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
if (jsonString!=nil){
NSLog(#"%#",jsonString);
}

Wunderground API json lookup on iPhone

Never touched json before. I'm trying to access some variables within the Wunderground weather API for Melbourne. For example, let's say I want to access the "wind_dir":"East" variable. This is my code thus far:
NSString *urlString =
[NSString stringWithFormat:
#"http://api.wunderground.com/api/key/geolookup/conditions/forecast/q/-33.957550,151.230850.json"];
NSLog(#"URL = %#", urlString);
SBJsonParser *parser = [[SBJsonParser alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:urlString]];
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSArray *weatherInfo = [parser objectWithString:json_string error:nil];
for (NSDictionary *weatherString in weatherInfo)
{
NSLog(#"some weather info = %#", [[[weatherString objectForKey:#"response"] objectForKey:#"current_observation"] objectForKey:#"wind_dir"]);
}
My code reaches the for loop and crashes with this error: -[NSCFString objectForKey:]: unrecognized selector sent to instance.
I'm not 100% sure what's causing the crash, and whether my path to the "wind_dir" variable is correct, though they could well be the same problem.
Thanks in advance for any help.
either the "response" property or the "current_observation" propery is string and not dictionary.
the error you are getting is that you are trying to call "objectForKey" on a string.
after looking at the result of the API, it seems that you are not getting an array.
You should do something like this:
NSDictionary *weatherInfo = [parser objectWithString:json_string error:nil];
NSLog(#"some weather info = %#", [[weatherInfo objectForKey:#"current_observation"] objectForKey:#"wind_dir"]);
instead of your for statement.