How can I parse JSON object in iPhone SDK? - iphone

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

Related

Posting data from iphone app to server

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.

Issues integrating Objective-C with ActiveCollab 3 Beta API

I am trying to implement an Objective C program to interface with activeCollab 3 beta and am having some issues. I can enter the url that the NSLog outputs in the browser and it works just fine pulling the xml for all the projects and it is not wanting to work for me when I try to access it via this program, it is giving me a HTTP 403 error. I am new to Objective C and am doing this as a learning experience so some code may be redundant. Thanks in advance for any help. The import is surrounded in angle brackets but will cause it to be hidden on StackOverflow so I have placed it in quotes
#import "Foundation/Foundation.h"
int main (int argc, const char * argv[]) {
NSString *token = #"my-token";
NSString *path_info = #"projects";
NSString *url = #"http://my-site/api.php?";
NSString *post = [[NSString alloc] initWithFormat:#"path_info=%#&auth_api_token=%#",path_info, token];
NSLog(#"Post: %#", post);
NSString *newRequest;
newRequest = [url stringByAppendingString:post];
NSLog(#"Path: %#", newRequest);
NSData *postData = [newRequest dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
[request setURL:[NSURL URLWithString:newRequest]];
[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 *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
NSString *returnData = [[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding] autorelease];
NSLog(#"%#", returnData);
//printf("Print line");
return 0;
}
Your request headers are restricting and unnecessary, and for AC API you want a GET request rather than POST
int main (int argc, const char * argv[])
{
NSString *requestString = [[NSString alloc] initWithFormat:#"path_info=%#&auth_api_token=%#", path_info, token];
NSLog(#"Post: %#", requestString);
NSString *newRequest;
newRequest = [url stringByAppendingString: requestString];
NSLog(#"Path: %#", newRequest);
NSData *postData = [newRequest dataUsingEncoding: NSASCIIStringEncoding allowLossyConversion: YES];
NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
NSLog(#"Data: %#", postData);
[request setURL: [NSURL URLWithString:newRequest]];
[request setHTTPMethod: #"GET"];
NSURLResponse *response;
NSError *err;
NSData *responseData = [NSURLConnection sendSynchronousRequest: request returningResponse: &response error: &err];
NSString *returnData = [[[NSString alloc] initWithData: responseData encoding: NSUTF8StringEncoding] autorelease];
NSLog(#"Return: %#", returnData);
//printf("Print line");
return 0;
}

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.

NSURLRequest: How to change httpMethod "GET" to "POST"

GET Method, it works fine.
url: http://myurl.com/test.html?query=id=123&name=kkk
I do not have concepts of POST method. Please help me.
How can I chagne GET method to POST method?
url: http://testurl.com/test.html
[urlRequest setHTTPMethod:#"POST"];
try this
NSString *post = [NSString stringWithFormat:#"username=%#&password=%#",username.text,password.text];
NSLog(#"%#",post);
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:#" server link here"]]];
[request setHTTPMethod:#"POST"];
NSString *json = #"{}";
NSMutableData *body = [[NSMutableData alloc] init];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
//get response
NSHTTPURLResponse* urlResponse = nil;
NSError *error = [[NSError alloc] init];
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
NSString *result = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSLog(#"Response Code: %d", [urlResponse statusCode]);
if ([urlResponse statusCode] >= 200 && [urlResponse statusCode] < 300)
{
NSLog(#"Response: %#", result);
}
// create mutable request
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
// set GET or POST method
[request setHTTPMethod:#"POST"];
// adding keys with values
NSString *post = #"query=id=123&name=kkk";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
[request addValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];

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