Quentin91360
Quentin91360

Reputation: 122

Send a php object and variable in NSData

I am actually trying to send a php variable(to say "You are now connected!"). I would like to know how to recover this variable in my iphone application using NSData.

My code is the following:

NSMutableURLRequest *Requete = [NSMutableURLRequest requestWithURL:url];

[Requete setHTTPMethod:@"POST"];

// On passe les variables

[Requete setHTTPBody:[[NSString stringWithFormat:@"email=%@ &   
password=%@",email,password]dataUsingEncoding:NSASCIIStringEncoding]];

NSURLResponse *response;
NSError *error;

NSData *result = [NSURLConnection sendSynchronousRequest:Requete returningResponse:&response error:&error];      

NSString *test = [[NSString alloc]initWithData:result encoding:NSASCIIStringEncoding];
NSLog(test);

I have an echo "Connected!" in my phpscript.I want to recover my variable return $connected=1. When I run this the console print Connected! and not 1; Anymore, I have no idea to do exactly the same process in order to recover a php object?

Thank u all,

Quentin

Upvotes: 1

Views: 435

Answers (1)

Authman Apatira
Authman Apatira

Reputation: 4054

PHP is executed on the server side which means all of your variables will no longer be available to your mobile (or otherwise) clients unless you explicitly define them do be there (by means of echo'ing them).

So you have two options:

  1. Edit your webscript to echo "$$connected=1"; This way, you will retreive that as the output in your NSData. Note, that this will NOT be an iphone variable though. To make it an iphone variable, you will have to do something like JSON encode your PHP output: {"connected":1} OR have your php file produce a PLIST. And then deseralize the NSData using the appropriate JSON / PLIST deseralizer.

  2. You can edit your iOS application to convert your NSData into a string and then compare it to @"Connected!". If it matches, create a local iOS variable (an int?) and just set it equal to 1.

Method 2 is the easiest, because you already have *test. Just:

if ([test rangeOfString:@"Connected!"] > 0 ) test = @"1";

With Method 1, you will have to

NSMutableDictionary *mydict = [NSJSONSerialization JSONObjectWithData:result options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:&error];
test = [mydict objectForKey:@"connected"];

BTW, if the spaces between your url variables wasn't intentionally added for StackOverflow readability, you should remove them, ie user=%@&pass=%@ instead of user=%@ & pass=%@.

PS -- If you are using iOS SDK < 5, you will have to handle the JSON seralization / deseralization using a third party tool, for example JSONKit, JSON, touchJSON, etc..

Upvotes: 1

Related Questions