exception __NSarrayM objectforkey unrecognized selector sent to instance [closed] - iphone

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 9 years ago.
Improve this question
i'm trying to make login page that get data fro php file by Json. it works fine until i use this sentence [jsonData objectForKey:#"state"] , an exception appears.
i tried to make another dictonary like some answers to question before. but nothing is working with me.
Output :
Response code : 200
Resonse ==> [{"state":"true"}]
JasonData ({state = true})
Then the exception
-[__NSarrayM objectforkey:]: unrecognized selector sent to instance
i'm new to objctive-C
if you could help me.
i will be greatfull
- (IBAction)loginClicked:(id)sender
{
#try
{
if([[txtUserName text] isEqualToString:#""] || [[txtPassword text] isEqualToString:#""] ) {
[self alertStatus:#"Please enter both Username and Password" :#"Login Failed!"];
} else {
NSString *post =[[NSString alloc] initWithFormat:#"username=%#&password=%#",[txtUserName text],[txtPassword text]];
NSLog(#"PostData: %#",post);
NSURL *url = [NSURL URLWithString:#"http://localhost/services/pages/login.php"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Response code: %d", [response statusCode]);
if ([response statusCode] >=200 && [response statusCode] <300)
{
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Response ==> %#", responseData);
SBJsonParser *jsonParser = [SBJsonParser new];
NSDictionary *jsonData = (NSDictionary *) [jsonParser objectWithString:responseData error:nil];
NSLog(#"%#",jsonData);
NSLog(#"%#",[jsonData objectForKey:#"state"]);
NSString *state = [(NSString*) [jsonData objectForKey:#"state"] lowercaseString ];
NSLog(#"%#", state);
if([state isEqualToString:#"true"])
{
NSLog(#"Login SUCCESS");
[self alertStatus:#"Logged in Successfully." :#"Login Success!"];
}
else
{
NSString *error_msg = (NSString *) [jsonData objectForKey:#"error_message"];
[self alertStatus:error_msg :#"Login Failed!"];
}
}
else
{
if (error) NSLog(#"Error: %#", error);
[self alertStatus:#"Connection Failed" :#"Login Failed!"];
}
}
}
#catch (NSException * e)
{
NSLog(#"Exception: %#", e);
[self alertStatus:#"Login Failed." :#"Login Failed!"];
}

The JSON data returned by the webserive seems to be an NSArray and not NSDictionary. You can check that here,
id jsonData = [jsonParser objectWithString:responseData error:nil];
if([jsonData isKindOfClass:[NSDictionary class]]) {
NSLog(#"Dictionary");
}
else if([jsonData isKindOfClass:[NSArray class]]) {
NSLog(#"Array");
}
Your code crashes because you are assuming the parsed response as NSDictionary and passing the objectForKey: method. Being an NSArray it cannot recognise this method and raises an exception.
Now if it is an NSArray with one dictionary inside, you can read it as below,
[[jsonData objectAtIndex:0] objectForKey:#"state"];
Hope that helps!

Related

csrf token validation failed for drupal services from iphone request

1.Is it necessary https://www.mysite.com/my_services/user/token
get that token and i set for login call but its get error 'csrf token issue'
before https://www.mysite.com/my_services/user/login
with post paramater username and password
i am question
whether i have to call user/token every time ..for getting token and set the x-csrf-token value in header for post requests.
(void)viewDidLoad
{
[super viewDidLoad];
NSString *notificationName = #"MTPostNotificationTut";
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:#selector(useNotificationWithString:)
name:notificationName
object:nil];
}
(void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
-(void)viewWillAppear:(BOOL)animated {
NSString *urlString = #"https://www.mysite.com/my_services/user/token.json";
NSString *urlS = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlS]cachePolicy:NSURLCacheStorageAllowed timeoutInterval:10.0];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *string = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"stringFromData = %#",string);
id jsonResponseData = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:nil];
NSLog(#"jsonResponseData = %#",jsonResponseData);
NSDictionary *jsonResponseDict;
if ([jsonResponseData isKindOfClass:[NSDictionary class]]) {
jsonResponseDict = jsonResponseData;
} else {
// Error-handling code
}
jsonResponseData = [jsonResponseDict objectForKey:#"d"];
if (jsonResponseData == nil) {
id jsonExceptioTypeData = [jsonResponseDict objectForKey:#"ExceptionType"];
if (jsonExceptioTypeData != nil) {
NSLog(#"%s ERROR : Server returned an exception", __func__);
NSLog(#"%s ERROR : Server error details = %#", __func__, jsonResponseDict);
}
}
token = [jsonResponseDict objectForKey:#"token"];
NSLog(#"token = %#",token);
if (token !=NULL) {
NSString *notificationName = #"MTPostNotificationTut";
NSString *key = #"token";
NSDictionary *dictionary = [NSDictionary dictionaryWithObject:token forKey:key];
[[NSNotificationCenter defaultCenter] postNotificationName:notificationName object:nil userInfo:dictionary];
}
}
-(void)checkWithServer:(NSString *)urlname jsonString:(NSString *)jsonString {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlname]cachePolicy:NSURLCacheStorageAllowed timeoutInterval:10.0];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *string = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"stringFromData = %#",string);
id jsonResponseData = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:nil];
NSDictionary *jsonResponseDict;
if ([jsonResponseData isKindOfClass:[NSDictionary class]]) {
jsonResponseDict = jsonResponseData;
} else {
}
jsonResponseData = [jsonResponseDict objectForKey:#"d"];
if (jsonResponseData == nil) {
id jsonExceptioTypeData = [jsonResponseDict objectForKey:#"ExceptionType"];
if (jsonExceptioTypeData != nil) {
NSLog(#"%s ERROR : Server returned an exception", __func__);
NSLog(#"%s ERROR : Server error details = %#", __func__, jsonResponseDict);
}
}
NSLog(#"jsonResponseData = %#",jsonResponseDict);
token = [jsonResponseDict objectForKey:#"token"];
NSLog(#"token = %#",token);
}
-(void)useNotificationWithString:(NSNotification*)notification {
NSString *urlString = #"https://www.mysite.com/my_services/user/login.json";
NSString *urlS = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSDictionary *inputData = [[NSDictionary alloc] initWithObjectsAndKeys:
#"ranjeet.gholave", #"username",
#"ran123", #"password",
nil];
NSError *error = nil;
NSData *jsonInputData = [NSJSONSerialization dataWithJSONObject:inputData options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonInputString = [[NSString alloc] initWithData:jsonInputData encoding:NSUTF8StringEncoding];
[self getTokenFromServer:urlS jsonString:jsonInputString];
}
-(void)getTokenFromServer:(NSString *)urlname jsonString:(NSString *)jsonString {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlname]cachePolicy:NSURLCacheStorageAllowed timeoutInterval:30.0];
[request setHTTPMethod:#"POST"];
// [request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:token forHTTPHeaderField:#"X-CSRFToken"];
[request setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSLog(#"responseDataIn Second Method = %#",responseData);
id jsonResponseData = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:nil];
NSLog(#"jsonResponseData = %#",jsonResponseData);
NSDictionary *jsonResponseDict;
if ([jsonResponseData isKindOfClass:[NSDictionary class]]) {
jsonResponseDict = jsonResponseData;
} else {
// Error-handling code
}
jsonResponseData = [jsonResponseDict objectForKey:#"d"];
if (jsonResponseData == nil) {
id jsonExceptioTypeData = [jsonResponseDict objectForKey:#"ExceptionType"];
if (jsonExceptioTypeData != nil) {
NSLog(#"%s ERROR : Server returned an exception", __func__);
NSLog(#"%s ERROR : Server error details = %#", __func__, jsonResponseDict);
}
}
}
if i cookie allowed then csrf token validation issue comes
and when i cookie not allowed then csrf token issue not comes ....how to resolved issue..thanks
Regards,
Ranjeet Gholave
I know this is a bit of an old thread. But you should check out https://github.com/kylebrowning/drupal-ios-sdk as well as AFNetworking. You're really working way harder than you have to.
But to answer your question, once you log in, the CSRF token will be returned in the user object and will be valid for then entire user session. So you can cache it and use it until the user logs out or their session expires.
With Drupal IOS SDK it is as simple as:
[DIOSUser userMakeSureUserIsLoggedInWithUsername:username
andPassword:password
success:^(AFHTTPRequestOperation *op, id response) {
DLog(#"user: %#", response);
[DIOSSession sharedSession].user = response;
//NOTE: fix for services 3.4+ CSRF Token Validation
[[DIOSSession sharedSession] setDefaultHeader:#"X-CSRF-Token" value:response[#"token"]];
[self saveLoginInfoForUserWithUsername:username andPassword:password];
[self processUserInfoWithUser:response];
success(response);
}
failure:^(AFHTTPRequestOperation *op, NSError *err) {
failure(err);
}
];

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+)

Do we need to give the request type either "json/xml"

My client is given one web service for my registration. I need to post the values.
I am using the following code to post:
-(IBAction)testingPurpose:(id)sender{
NSMutableDictionary *finalQuoteDict = [[NSMutableDictionary alloc] init];
[finalQuoteDict setValue:#"It is an Error Message" forKey:#"ErrorMsg"];
[finalQuoteDict setValue:#"json" forKey:#"ReturnVal"];
[finalQuoteDict setValue:#"john#live.com" forKey:#"Email"];
[finalQuoteDict setValue:#"David John" forKey:#"FullName"];
[finalQuoteDict setValue:#"2147483647" forKey:#"UserID"];
[finalQuoteDict setValue:#"john" forKey:#"UserName"];
[finalQuoteDict setValue:#"qqqqqq" forKey:#"UserPassword"];
SBJsonWriter *jsonWriter = [[SBJsonWriter alloc] init];
NSString *jsonRequest = [jsonWriter stringWithObject:finalQuoteDict];
jsonRequest = [jsonRequest stringByReplacingOccurrencesOfString:#"<" withString:#""];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#Register",MainUrl1,jsonRequest]];
NSLog(#"url is---%#",url);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSData *requestData = [NSData dataWithBytes:[jsonRequest UTF8String] length:[jsonRequest length]];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody: requestData];
NSError* error = nil;
NSURLResponse* response;
NSData* result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *dataString=[[NSString alloc]initWithData:result encoding:NSUTF8StringEncoding];
NSMutableDictionary *getResponseDict = [[NSMutableDictionary alloc] init];
[getResponseDict addEntriesFromDictionary:[dataString JSONValue]];
}
But it throws an error says
"Error trace is: (
"Error Domain=org.brautaset.JSON.ErrorDomain Code=3 \"Unrecognised leading character\" UserInfo=0x856ac50 {NSLocalizedDescription=Unrecognised leading character}"
Please check the image i.e, to post the values..
Do we need to give the request type either "json/xml"
Thanks a lot in advance
Try to use this
Here httpMethod is "POST".
postData is all ur Post data with Key value same as for web service request.
aUrl is ur service url
-(void)WebService:(NSString *)httpMethod DataDictionary:(id)postData RequestAction:(NSString *)aUrl
{
// Check internet Connection
//Use Reachability class for this==============
Reachability *r = [Reachability reachabilityWithHostName:#"www.google.com"];
NetworkStatus internetStatus = [r currentReachabilityStatus];
if ((internetStatus != ReachableViaWiFi) && (internetStatus != ReachableViaWWAN))
{
NSLog("No Internet Connection Available");
return;
}
self.identifier = serviceIdentifier;
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:aUrl] cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:10.0 ];
NSLog(#"final request is %#",request);
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
//set body in JSON formate
[request setHTTPBody:[[self convertToJSON:postData] dataUsingEncoding:NSUTF8StringEncoding]];
NSString *contentLength = [NSString stringWithFormat:#"%d",[[request HTTPBody] length]];
[request setValue:contentLength forHTTPHeaderField:#"Content-Length"];
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
if (connection)
{
self.responseData = [NSMutableData data]; //Its a mutable Data object
}
}
//Convert data into JSOn format
//use JSON classes for this
-(NSString *)convertToJSON:(id)requestParameters
{
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:requestParameters options:NSJSONWritingPrettyPrinted error:nil];
NSLog(#"JSON DATA LENGTH = %d", [jsonData length]);
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
NSLog(#"JSON STR LENGTH = %d", [jsonString length]);
return jsonString;
}
//you will get response in NSURLConnection
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[self.responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[self.responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
NSLog("Failed to get Result......");
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSString *jsonString = [[[NSString alloc] initWithData:self.responseData encoding:NSUTF8StringEncoding] autorelease];
NSDictionary *aDic = [jsonString JSONValue];
NSLog("Your Response Data is ==>> %d",aDic);
}
Hope this will helps you
You don't need to supply json or xml in request type unless or until webservice requires it explicitly. It would be better if webservice handles it.
But i think problem is in parsing the response.
First make sure that dataString is not null or empty or you are getting some response from the server.
If it has some values then probably the return value or server response is not a valid JSON format.
You can validate json response by pasting it to the
http://jsonlint.com/ .

how to send user name and password using post to server in iphone app

I am making a lo-gin app i want to send the username and password to server for validation how to do this i have done in many ways but i am unable to post.
I am posting the username and password but it did not work if i direct give username and password to php it works so how to do this in iphone to send through post
NSString *post = [[NSString alloc] initWithFormat:#"UserName=%#&Password=%#",username,pass];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSURL *url = [NSURL URLWithString:#"http://www.celeritas-solutions.com/emrapp/connect.php?"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:#"POST"];
theRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPBody:postData];
NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if( theConnection )
{
webData = [[NSMutableData data] retain];
}
else
{
NSLog(#"Inside the else condition");
}
[nameInput resignFirstResponder];
[passInput resignFirstResponder];
nameInput.text = nil;
passInput.text = nil;
//Edited your code try this may help you.
NSString *post = [[NSString alloc] initWithFormat:#"UserName=%#&Password=%#",username,pass];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSURL *url = [NSURL URLWithString:#"http://www.celeritas-solutions.com/emrapp/connect.php?"];
NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
[theRequest setHTTPMethod:#"POST"];
[theRequest setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
theRequest setValue:postLength forHTTPHeaderField:#"Content-Length"];
[theRequest setHTTPBody:postData];
//when the user clicks login<action>
- (IBAction)signinClicked:(id)sender {
NSInteger success = 0;
#try {
//to check if username and password feild are filled
if([[self.txtUsername text] isEqualToString:#""] || [[self.txtPassword text] isEqualToString:#""] ) {
[self alertStatus:#"Please enter Username and Password" :#"Sign in Failed!" :0];
} else {
NSString *post =[[NSString alloc] initWithFormat:#"username=%#&password=%#",[self.txtUsername text],[self.txtPassword text]];
NSLog(#"PostData: %#",post);
//post it to your url where your php file is saved for login
NSURL *url=[NSURL URLWithString:#"http://xyz.rohandevelopment.com/new.php"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
//[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:[url host]];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *response = nil;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"Response code: %ld", (long)[response statusCode]);
if ([response statusCode] >= 200 && [response statusCode] < 300)
{
NSString *responseData = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Response ==> %#", responseData);
NSError *error = nil;
NSDictionary *jsonData = [NSJSONSerialization
JSONObjectWithData:urlData
options:NSJSONReadingMutableContainers
error:&error];
success = [jsonData[#"success"] integerValue];
NSLog(#"Success: %ld",(long)success);
if(success == 1)
{
NSLog(#"Login SUCCESS");
} else {
NSString *error_msg = (NSString *) jsonData[#"error_message"];
[self alertStatus:error_msg :#"Sign in Failed!" :0];
}
} else {
//if (error) NSLog(#"Error: %#", error);
[self alertStatus:#"Please Check Your Connection" :#"Sign in Failed!" :0];
}
}
}
#catch (NSException * e) {
NSLog(#"Exception: %#", e);
[self alertStatus:#"Sign in Failed." :#"Error!" :0];
}
if (success) {
[self performSegueWithIdentifier:#"login_success" sender:self];
}
}
- (void) alertStatus:(NSString *)msg :(NSString *)title :(int) tag
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
message:msg
delegate:self
cancelButtonTitle:#"Ok"
otherButtonTitles:nil, nil];
alertView.tag = tag;
[alertView show];
}
Add Following Code After
[theRequest setHTTPBody:postData];
NSURLResponse *response;// = [[NSURLResponse alloc] init];
NSError *error;// = [[NSError alloc] init;
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Login response: is %#",str);

json PUT request

Hi iam usng JSONKit. i need to update status in linkedin site by sending the status update through json request to server. this is the code im sendin. im gettin 400 eroor. please tel me whats the mistake.
thanks.
NSMutableDictionary *jsonDict = [[NSMutableDictionary alloc] initWithObjectsAndKeys:#"linkedin-html",#"contentType",#"My Fancy Update",#"body",nil];
NSString *str =[jsonDict JSONString];
NSMutableData *requestData = [NSMutableData dataWithBytes:[str UTF8String] length:[str length]];
[self setHTTPBody:requestData];
[self setValue:[NSString stringWithFormat:#"%d", [requestData length]] forHTTPHeaderField:#"Content-Length"];
[self setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
dont know if this will fit your usage needs exactly, I am using iphone and connecting to jayrock .net webservices.
Here is the command I use to handle all my calls.
Also, I am using the json-framework
- (NSDictionary*) sendJSONRPCRequestTo:(NSString*) url
forCommand:(NSString*)command
withParamaters:(NSMutableArray*) parameters
synchronous:(BOOL) sendSynchronous
{
if (parameters != nil)
{
[parameters setValue:[HSAppData appVersion] forKey:#"AppVersion"];
[parameters setValue:[NSNumber numberWithDouble:[HSAppData currentLocation].longitude] forKey:#"Longitude"];
[parameters setValue:[NSNumber numberWithDouble:[HSAppData currentLocation].latitude] forKey:#"Latitude"];
}
if (self.commandId == nil)
{
self.commandId = #"1";
}
NSMutableURLRequest *request = [self.baseTransaction makeNewRequestFor:url];
NSMutableDictionary *mainPackage = [NSMutableDictionary dictionary];
[mainPackage setValue:self.commandId forKey:#"id"];
[mainPackage setValue:command forKey:#"method"];
[mainPackage setValue:parameters forKey:#"params"];
NSString *jsonData = [mainPackage JSONRepresentation];
[request setValue:command forHTTPHeaderField:#"X-JSON-RPC"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
if (jsonData != nil && [jsonData isEqual:#""] == NO)
{
[request setHTTPMethod:#"POST"];
[request setValue:[[NSNumber numberWithInt:[jsonData length]] stringValue] forHTTPHeaderField:#"Content-Length"];
}
[request setHTTPBody:[jsonData dataUsingEncoding:NSUTF8StringEncoding]];
if (sendSynchronous)
{
NSHTTPURLResponse * response = nil;
NSError * error = nil;
//self.baseTransaction.lastConnection = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *jsonResult = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
NSDictionary *jsonDict = nil;
#try {
jsonDict = [jsonResult JSONValue];
}
#catch (NSException * e) {
NSLog(#"Error: %#",jsonResult);
jsonDict = [NSMutableDictionary dictionary];
[jsonDict setValue:self.commandId forKey:#"id"];
[jsonDict setValue:#"Unable to call function on server" forKey:#"error"];
[jsonDict setValue:[NSNull null] forKey:#"result"];
}
#finally {
return jsonDict;
}
}
// TODO: Add ASynchronous
// else
// {
// }
}
I would start by writing your json payload and the connection response data to a simple text file and review (or post, if you want us to take a look). I've found that's the easiest way for me to spot issues when posting data to services. You're using a library, so my guess is the payload should be fine, but you never know. The response data may include more hints to the true issue, although I can't say I've ever used LinkedIn's api.
Also, I didn't see where you specified that the request was a "PUT". Did you include
[req setHTTPMethod:#"PUT"];
Use this code to write the payload to the file system (sorry for the formatting, it's not playing nicely with mobile safari):
NSString *documentsDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *documentPath = [NSString stringWithFormat:#"%#/payloadData.txt", documentsDirectoryPath];
[requestData writeToFile:documentPath atomically:YES];
May be this can help you.