Posting data from iphone app to server - iphone

I am sending data from iphone application to server but when it reads post String it crashes in the application and do not move forward
-(void)submitSurveyAnswers{
NSString*survey_question_response_id="1";
NSString*survey_id=#"1";
NSString *question_id =#"1";
NSString *survey_response_answer_id =#"1";
NSString *post =[[NSString alloc] initWithFormat:#"survey_question_response_id=%#&survey_id=%#&question_id=%#&survey_response_answer_id=%#",survey_question_response_id,survey_id,question_id,survey_response_answer_id];
NSLog(post);
NSURL *url=[NSURL URLWithString:#"http://myserver-solutions.com/app/surveyAnswer.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/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSLog(#"%#",data);
}

You have created one string with below way:
NSString*survey_question_response_id="1"; //Missing '#' while initializing string
It should be created like below way:
NSString*survey_question_response_id=#"1"; //Added '#' while initializing string

NSString*survey_question_response_id="1";
is wrong. Strings between plain double quotes are C string (0-terminated character pointers), and aren't valid NSString instances. I'm sure you wanted to 1. learn to use a debugger 2. write
NSString *survey_question_response_id = #"1";
instead.

Related

converting image to base64 and uploading in JSON format to server

I have a problem. I need to convert base64 string to JSON string and pass it to server.
for example I have a base64 string /9j/4AAQSkZJRgABAQAAAQABAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAACqADAAQAAAABAAAACgAAAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/Z
i need to convert it to JSON format. I do the following:
+(NSData *)prepareForUploading:(NSString *)base64Str
{
NSDictionary *dict=[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:base64str, nil] forKeys:[NSArray arrayWithObjects:#"picture", nil]];
NSData *preparedData=[NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:nil];
return preparedData;
};
here how I'm making NSURLRequest
-(NSString *)uploadPict:(NSString *)pict
{
NSLog(#"Server: upload: called");
NSData *prepPictData=[[self class] prepareForUploading:pict];
NSString *preparedBase64StrInJSON=[[NSString alloc] initWithData:prepPictData encoding:NSUTF8StringEncoding];
//here I'm adding access token to request
NSString *post = [NSString stringWithFormat:#"accessToken=%#&object=%#", self.key, preparedBase64StrInJSON];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#upload.aspx", serverAPIPath]]];
[request setHTTPMethod:#"POST"];
[request setValue:#"postLength" forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSError *error;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//....
}
But I get "Invalid length for a Base-64 char array" from server. What's wrong?
If I paste my token and JSON to http://hurl.it/ and make request using it - everything goes normally.
I think the problem is / symbols in base64 string and as a result / symbols in JSON.
Maybe it is something with [postData length]: if I erase \/ characters from JSON string:
9j4AAQSkZJRgABAQAAAQABAAD4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAACqADAAQAAAABAAAACgAAAAD2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQHZ request will perform normally but this base64 encoded string is not the same.
Please, help me to solve this problem
jString is your base64 string, first use following line
[self encodeString:jString];
and then call use following.
NSString *URL = [NSString stringWithFormat:#"forms.asmx/CreateUpdate?"];
URL=[NSString stringWithFormat:#"%#%#", USERS_API_ROOT_URL, URL];
NSString *post = [NSString stringWithFormat:#"apiKey=A0B1I2L3A4L5-A1D3-4F30-5AB2-C8DEE266&strPost=%#",jString];
unsigned long long postLength = [post length];
NSString *contentLength = [NSString stringWithFormat:#"%llu",postLength];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init] ;
[request setURL:[NSURL URLWithString:URL]];
[request setHTTPMethod:#"POST"];
[request setValue:contentLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData ];
(void)[[NSURLConnection alloc] initWithRequest:request delegate:self];
-(NSString *)encodeString:(NSString *)string
{
NSString *newString = (__bridge_transfer NSString*)CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (CFStringRef)string, NULL,CFSTR(":/?#[]#!$ &'()*+,;=\"<>%{}|\\^~`"), CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
return newString;
}
Hope it will work.

How can I parse JSON object in iPhone SDK?

I need to parse the data I receive the following way:
[
{
"IdEmpleado":1,
"Nombre":"Cesar",
"Edad":"25",
"Genero":"M",
"IdArea":1
},
{
"IdEmpleado":2,
"Nombre":"Luis",
"Edad":"30",
"Genero":"M",
"IdArea":2
}
]
I need to get the data for each employee, in the example are 2 employees need all the fields of each object and then turn them into employees.
I already use the JSON and transfer to an NSDICTIONARY, but how I can do to have it structured so each field and being able to pass a Method to convert an object EMPLOYEE?
http://stig.github.com/json-framework/
You can use the JSONFramework, which you can find here.
https://github.com/stig/json-framework/
NSString *userid= [[NSUserDefaults standardUserDefaults]objectForKey:#"Userid"];
NSString *appurl =[NSString stringWithFormat:#"your link"];
appurl = [appurl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSMutableURLRequest *request=[NSMutableURLRequest requestWithURL:[NSURL URLWithString:appurl]];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse: nil error: nil ];
NSString *returnString = [[NSString alloc] initWithData:returnData encoding: NSUTF8StringEncoding];
NSMutableDictionary *deletdict=[returnString JSONValue];
if([[deletdict objectForKey:#"success"] isEqualToString:#"False"])
{
NSLog(#"Unsuccess...");
}
else
{
NSLog(#"success...");
}
AND Post method is this
NSString *post =[NSString stringWithFormat:#"AgencyId=STM&UserId=1&Type=1&Date=%#&Time=%#&Coords=%#&Image=h32979`7~U#)01123737373773&SeverityLevel=2",strDateLocal,strDateTime,dict];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://174.94.153.48:7778/TransitApi/IncidentConfirm/"]]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *str=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
NSMutableArray *SubLiveArray=[str JSONValue];
download Json framework on this link:::
http://mobile.tutsplus.com/tutorials/iphone/iphone-json-twitter-api
NSString *appurl=[NSString stringWithFormat:#"https://maps.googleapis.com/maps/api/place/search/json?location=23.041230,72.514346&radius=50000&types=%#&sensor=true&key=AIzaSyAQZ16VzshxGbYdiM8C2RhhwGl3QwVJTB4",_txt_search.text];

Fetch POST value in coldfusion from objective C

I am trying to post a string to a URL in iphone which will be retrieved by the server. The server side scripting is done in coldfusion. I am trying to fetch the data in coldfusion and pass on the value back to iphone. I am not familiar much with coldfusion and wanted some help in this. Below is the coding in iphone :
/** Iphone code **/
NSString *post =[[NSString alloc] initWithString:#"Hello World"];
NSURL *url=[NSURL URLWithString:#"http://www.abc.com/test.cfm"];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *data=[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding];
/*Coldfusion code */
<html>
<head><title>Test</title></head>
<body>
<cfoutput>#form.post#</cfoutput>
</body>
</html>
Am I doing it correctly ?
You may need to specify name of form variable in data. Try below for post variable. I haven't tested it should work.
NSString *post =[[NSString alloc] initWithString:#"post=Hello%20World"];

json data reply nil

NSString *urlString =[NSString stringWithFormat:#"http://api.stackoverflow.com/1.0/questions?tagged=iphone & key=%d",key1];
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:#"POST"];
[request setValue:#"text/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"text/json" forHTTPHeaderField:#"Accept"];
NSError *error ;
NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
NSLog(#"jsondata=%#,%#",json_string,response);
2011-02-11 12:01:16.653
mystack[1946:207] jsondata=,(null)
Your URL string is not valid since it contains blank spaces: &. You need to escape those before creating an NSURL object. Replace:
NSString *urlString =[NSString stringWithFormat:#"http://api.stackoverflow.com/1.0/questions?tagged=iphone & key=%d",key1];
with:
NSString *urlString =[NSString stringWithFormat:#"http://api.stackoverflow.com/1.0/questions?tagged=iphone & key=%d",key1];
urlString = [urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
thanks for helping me here is the answer
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
the code that i have to change..
You should NSLog your error variable to see what happened: [error localizedDescription]

how to pass arguments to url (.php file)

http://something.php?ownerID=13&view=userAgreement
i need to pass two variables to this ..
how can i pass these i am declared ownerid to 13 in my config playlist and i am able to get it ,how to set "view = useragreement" string to view variable....
can any body show me sample code..
i am using like
NSString* termsURL = [[[NSBundle mainBundle] infoDictionary] objectForKey:#"termsURL"];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#%#%#%#%#", termsURL, #"?ownerID=", ownerID,#"?view=",userAgreement]];
but is not working,i am checking parsing is success or not with this url but is failing...
Code taken straight from my app. It works for what you need
NSString *post = [NSString stringWithFormat:#"ownerID=13&view=userAgreement"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
//set up the request to the website
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:#"http://something.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSError *error;
NSURLResponse *response;
NSData *urlData=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSString *result3=[[[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding]autorelease];