csrf token validation failed for drupal services from iphone request - iphone

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);
}
];

Related

DocuSign error downloading document

I'm trying to implement this example link of a DocuSign service that download an envelope document, but when the execution arrive to this line in step 3:
NSMutableString *jsonResponse = [[NSMutableString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];
jsonResponse is nil and when I open the document, it has a lot of strange characters and I can't read it.
My code for downloadind is the following:
NSString *url = #"https://demo.docusign.net/restapi/v2/accounts/373577/envelopes/08016140-e4dc-4697-8146-f8ce801abf92/documents/1";
NSMutableURLRequest *documentsRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
[documentsRequest setHTTPMethod:#"GET"];
[documentsRequest setURL:[NSURL URLWithString:url]];
[documentsRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[documentsRequest setValue:[self jsonStringFromObject:authenticationHeader] forHTTPHeaderField:#"X-DocuSign-Authentication"];
NSError *error1 = [[NSError alloc] init];
NSHTTPURLResponse *responseCode = nil;
NSData *oResponseData = [NSURLConnection sendSynchronousRequest:documentsRequest returningResponse:&responseCode error:&error1];
NSMutableString *jsonResponse = [[NSMutableString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];
if([responseCode statusCode] != 200){
NSLog(#"Error sending %# request to %#\nHTTP status code = %i", [documentsRequest HTTPMethod], url, [responseCode statusCode]);
NSLog( #"Response = %#", jsonResponse );
return;
}
// download the document to the same directory as this app
NSString *appDirectory = [[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent];
NSMutableString *filePath = [NSMutableString stringWithFormat:#"%#/%#", appDirectory, #"eee"];
[oResponseData writeToFile:filePath atomically:YES];
NSLog(#"Envelope document - %# - has been downloaded to %#\n", #"eee", filePath);
If no data is coming back from
NSMutableString *jsonResponse = [[NSMutableString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];
then that means oResponseData is most likely nil which means the URL is not being constructed correctly for each envelope document. Are you doing step 2 in the sample that you linked to, where it first retrieves the envelopeDocuments information about the envelope, then it dynamically builds each unique document uri in preparation of downloading each one.
Instead of hardcoding your URL you should dynamically retrieve the envelopeDocuments data, then build each document uri dynamically then your response data will not be nil. Here's the full working sample:
- (void)getDocumentInfoAndDownloadDocuments
{
// Enter your info:
NSString *email = #"<#email#>";
NSString *password = #"<#password#>";
NSString *integratorKey = #"<#integratorKey#>";
// need to copy a valid envelopeId from your account
NSString *envelopeId = #"<#envelopeId#>";
///////////////////////////////////////////////////////////////////////////////////////
// STEP 1 - Login (retrieves accountId and baseUrl)
///////////////////////////////////////////////////////////////////////////////////////
NSString *loginURL = #"https://demo.docusign.net/restapi/v2/login_information";
NSMutableURLRequest *loginRequest = [[NSMutableURLRequest alloc] init];
[loginRequest setHTTPMethod:#"GET"];
[loginRequest setURL:[NSURL URLWithString:loginURL]];
// set JSON formatted X-DocuSign-Authentication header (XML also accepted)
NSDictionary *authenticationHeader = #{#"Username": email, #"Password" : password, #"IntegratorKey" : integratorKey};
// jsonStringFromObject() function defined further below...
[loginRequest setValue:[self jsonStringFromObject:authenticationHeader] forHTTPHeaderField:#"X-DocuSign-Authentication"];
// also set the Content-Type header (other accepted type is application/xml)
[loginRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[NSURLConnection sendAsynchronousRequest:loginRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *loginResponse, NSData *loginData, NSError *loginError) {
if (loginError) { // succesful GET returns status 200
NSLog(#"Error sending request %#. Got Response %# Error is: %#", loginRequest, loginResponse, loginError);
return;
}
// we use NSJSONSerialization to parse the JSON formatted response
NSError *jsonError = nil;
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:loginData options:kNilOptions error:&jsonError];
NSArray *loginArray = responseDictionary[#"loginAccounts"];
// parse the accountId and baseUrl from the response (other data included)
NSString *accountId = loginArray[0][#"accountId"];
NSString *baseUrl = loginArray[0][#"baseUrl"];
//--- display results
NSLog(#"\naccountId = %#\nbaseUrl = %#\n", accountId, baseUrl);
///////////////////////////////////////////////////////////////////////////////////////
// STEP 2 - Get Document Info for specified envelope
///////////////////////////////////////////////////////////////////////////////////////
// append /envelopes/{envelopeId}/documents URI to baseUrl and use as endpoint for next request
NSString *documentsURL = [NSMutableString stringWithFormat:#"%#/envelopes/%#/documents", baseUrl, envelopeId];
NSMutableURLRequest *documentsRequest = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:documentsURL]];
[documentsRequest setHTTPMethod:#"GET"];
[documentsRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[documentsRequest setValue:[self jsonStringFromObject:authenticationHeader] forHTTPHeaderField:#"X-DocuSign-Authentication"];
[NSURLConnection sendAsynchronousRequest:documentsRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *documentsResponse, NSData *documentsData, NSError *documentsError) {
NSError *documentsJSONError = nil;
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:documentsData options:kNilOptions error:&documentsJSONError];
if (documentsError){
NSLog(#"Error sending request: %#. Got response: %#", documentsRequest, documentsResponse);
NSLog( #"Response = %#", documentsResponse );
return;
}
NSLog( #"Documents info for envelope is:\n%#", jsonResponse);
NSError *jsonError = nil;
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:documentsData options:kNilOptions error:&jsonError];
// grab documents info for the next step...
NSArray *documentsArray = responseDictionary[#"envelopeDocuments"];
///////////////////////////////////////////////////////////////////////////////////////
// STEP 3 - Download each envelope document
///////////////////////////////////////////////////////////////////////////////////////
NSMutableString *docUri;
NSMutableString *docName;
NSMutableString *docURL;
// loop through each document uri and download each doc (including the envelope's certificate)
for (int i = 0; i < [documentsArray count]; i++)
{
docUri = [documentsArray[i] objectForKey:#"uri"];
docName = [documentsArray[i] objectForKey:#"name"];
docURL = [NSMutableString stringWithFormat: #"%#/%#", baseUrl, docUri];
[documentsRequest setHTTPMethod:#"GET"];
[documentsRequest setURL:[NSURL URLWithString:docURL]];
[documentsRequest setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[documentsRequest setValue:[self jsonStringFromObject:authenticationHeader] forHTTPHeaderField:#"X-DocuSign-Authentication"];
NSError *error = [[NSError alloc] init];
NSHTTPURLResponse *responseCode = nil;
NSData *oResponseData = [NSURLConnection sendSynchronousRequest:documentsRequest returningResponse:&responseCode error:&error];
NSMutableString *jsonResponse = [[NSMutableString alloc] initWithData:oResponseData encoding:NSUTF8StringEncoding];
if([responseCode statusCode] != 200){
NSLog(#"Error sending %# request to %#\nHTTP status code = %i", [documentsRequest HTTPMethod], docURL, [responseCode statusCode]);
NSLog( #"Response = %#", jsonResponse );
return;
}
// download the document to the same directory as this app
NSString *appDirectory = [[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent];
NSMutableString *filePath = [NSMutableString stringWithFormat:#"%#/%#", appDirectory, docName];
[oResponseData writeToFile:filePath atomically:YES];
NSLog(#"Envelope document - %# - has been downloaded to %#\n", docName, filePath);
} // end for
}];
}];
}
- (NSString *)jsonStringFromObject:(id)object {
NSString *string = [[NSString alloc] initWithData:[NSJSONSerialization dataWithJSONObject:object options:0 error:nil] encoding:NSUTF8StringEncoding];
return string;
}

exception __NSarrayM objectforkey unrecognized selector sent to instance [closed]

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!

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

HTTP Post method php and ios

i'm facing a big problem,
I want to send data to my server, my data is a string.
I do not want to use Get method because the string might be very long, so i want to use POST method but everything goes, wrong, if someone can help me he'll be my hero :)
Here is my php code :
<?php include("config.inc.php");
if (isset($_POST['contentInterro']) && $_POST['contentInterro'] !="" ) {
//$id_user = $_POST['contentInterro'];
//$db->sql_query("INSERT INTO interrogations VALUES(DEFAULT, '$id_user')");
echo "succes";
}else{
echo "This is an error";
}
?>
Here is my app code :
NSData *postData = [stringToPost2 dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *requestPost = [[NSMutableURLRequest alloc] init];
NSURL *urlPost = [NSURL URLWithString:#"http://buzznapps.fr/FDF/postInterrogation.php"];
[requestPost setURL:urlPost];
[requestPost setHTTPMethod:#"POST"];
[requestPost setValue:#"lol" forHTTPHeaderField:#"contentInterro"];
NSError *errorURL;
NSURLResponse *response;
NSData *urlData = [NSURLConnection sendSynchronousRequest:requestPost returningResponse:&response error:&errorURL];
NSString *str = [[NSString alloc] initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"Str = %#",str);
I always get an error, and i've search the web i do not know how to get this data !
Thanks for any help.
#define TIMEOUT_INTERVAL 60
#define CONTENT_TYPE #"Content-Type"
#define URL_ENCODED #"application/x-www-form-urlencoded"
#define GET #"GET"
#define POST #"POST"
-(NSMutableURLRequest*)getNSMutableURLRequestUsingGetMethodWithUrl:(NSString*)url
{
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:TIMEOUT_INTERVAL];
[req setHTTPMethod:GET];
return req;
}
-(NSMutableURLRequest*)getNSMutableURLRequestUsingPOSTMethodWithUrl:(NSString *)url postData:(NSString*)_postData
{
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:TIMEOUT_INTERVAL];
[req setHTTPMethod:POST];
[req addValue:URL_ENCODED forHTTPHeaderField:CONTENT_TYPE];
[req setHTTPBody: [_postData dataUsingEncoding:NSUTF8StringEncoding]];
return req;
}
#try
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
NSString *_postData = [NSString stringWithFormat:#"user_name=%#&password=%#",#"user_name",#"password"];
NSMutableURLRequest *req = [self getNSMutableURLRequestUsingPOSTMethodWithUrl:_url postData:_postData];
[NSURLConnection sendAsynchronousRequest:req queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if (error)
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSLog(#"error==%#==",[error localizedDescription]);
}
else
{
NSError *errorInJsonParsing;
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&errorInJsonParsing];
if(errorInJsonParsing) //error parsing in json
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
NSLog(#"error in json==%#==",[error localizedDescription]);
}
else
{
//do some operations
}
}
}];
}
#catch(NSException *exception)
{
NSLog(#"error in exception==%#==",[exception description]);
}
same way it works for the get method, just call the
NSMutableURLRequest *req = [self getNSMutableURLRequestUsingGetMethodWithUrl:_url]; instead of NSMutableURLRequest *req = [self getNSMutableURLRequestUsingPOSTMethodWithUrl:_url postData:_postData];

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