Fetch data using JSON parsing via post method in iOS7 using NSJsonSerialization - json

I am new to iOS Development. Need help to parse this data using NSJSONSerialization. Data comes via post method.
Data is like this
[
{
"edition_id": "1",
"error": false,
"long_name": "Rajkot",
"message": "RESULT_OK",
"short_name": "RJT"
}
]
and code of my file is like this
NSURL *theURL = [NSURL URLWithString:#"MYURL"];
NSMutableURLRequest *theRequest = [[NSMutableURLRequest alloc] init];
[theRequest setURL:theURL];
[theRequest setHTTPMethod:#"POST"];
NSData *allCoursesData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:theRequest]];
NSError *error;
NSMutableDictionary *allCourses = [NSJSONSerialization JSONObjectWithData:allCoursesData options:kNilOptions error:&error];

NSString * uid = #"2"; // variable value
NSString *post = [NSString stringWithFormat:#"uid=%#",uid]; // post variable
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d", [postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://localhost/my/json_post/index.php"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded;charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLResponse *response;
NSData *POSTReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
/* NSString *theReply = [[NSString alloc] initWithBytes:[POSTReply bytes] length:[POSTReply length] encoding: NSASCIIStringEncoding];
NSLog(#"json Reply : %#", theReply);
*/
NSArray *arr = [NSJSONSerialization JSONObjectWithData:POSTReply options:0 error:nil];
NSLog(#"%#",arr);
NSLog(#"%#",[arr valueForKey:#"id"]); //this is table column name
NSLog(#"%#",[arr valueForKey:#"name"]);
NSLog(#"%#",[arr valueForKey:#"surname"]);

Fetch data using JSON parsing via post method
NSHTTPURLResponse *response = nil;
NSError *error=nil;
NSString *post = [NSString stringWithFormat:#"Key=%#",#"value"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"Your URL"]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
NSData *conn1 = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
NSLog(#"%#",conn1);
NSString *responseString = [[NSString alloc] initWithData:conn1 encoding:NSUTF8StringEncoding];
NSLog(#"here %#",responseString);
if(conn) {
NSLog(#"Connection Successful");
} else {
NSLog(#"Connection could not be made");
}

Related

Obj-C POST JSON (body?)to endpoint problems

Using Postman on my Mac I have confirmed GET/POST works to my endpoint. On my iPad I am trying to do the same thing but only GET connects and returns data (just for
testing).
In Postman I have key of devices and value of [{"name":"1","values":[121,182,243]}]
From Postman I can Send and the physical object responds and the server returns an array of all devices and nothing else (which I do not require but that is how it goes). Postman does have x-www-form-urlencoded under Body. This works as expected from Postman.
From my iPad the following code always returns an error 400 which I think means I am providing something the server is not expecting.
+(void)makeRequest {
NSError *error = nil;
storedURL = [[NSUserDefaults standardUserDefaults] objectForKey:#"eb-ipaddress-saved"];
NSString *urlstring = [NSString stringWithFormat:#"http://%#",storedURL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlstring] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSString *jsonPostBody = #"{\"devices\":[{\"name\":\"1\",\"values\":[121,182,243]}]}";
NSData *postData = [jsonPostBody dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:NO];
NSString *postLength = [NSString stringWithFormat:#"%lu",(unsigned long)[postData length]];
[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];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if(httpResponse.statusCode == 200)
{
NSError *parseError = nil;
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSLog(#"The response is - %#",responseDictionary);
NSInteger success = [[responseDictionary objectForKey:#"success"] integerValue];
if(success == 1)
{
NSLog(#"SUCCESS");
}
else
{
NSLog(#"FAILURE");
}
}
else
{
NSLog(#"Error");
}
}];
[dataTask resume];
}
My 4 logs from above (removed for clarity) return:
urlstring http://192.168.90.55:3000/dmx/set
jsonPostBody {"devices":[{"name":"1","values":[121,182,243]}]}
httpResponse 400
Error
I will eventually switch to variables in my POST when in production.
Thank you
Thanks to Larme's answer I used the code from Postman and that worked.
+(void)makeRequest
{
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"http://192.168.90.55:3000/dmx/set"]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:10.0];
NSDictionary *headers = #{
#"Content-Type": #"application/x-www-form-urlencoded"
};
[request setAllHTTPHeaderFields:headers];
NSMutableData *postData = [[NSMutableData alloc] initWithData:[#"devices=[{\"name\":\"1\",\"values\":[121,182,243]}]" dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postData];
[request setHTTPMethod:#"POST"];
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request
completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
if (error) {
NSLog(#"%#", error);
dispatch_semaphore_signal(sema);
} else {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *) response;
NSError *parseError = nil;
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:0 error:&parseError];
NSLog(#"%#",responseDictionary);
dispatch_semaphore_signal(sema);
}
}];
[dataTask resume];
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
}

Which is the best method to fetch data from JSON url?

I have a application in which when we login a new view controller will be loaded which is a table view and data need to be fetched from server by Json call.Which is the best method to use in this situation.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"http://YourURL.com/FakeURL/PARAMETERS"]];
[request setHTTPMethod:#"GET"];
NSURLResponse *requestResponse;
NSData *requestHandler = [NSURLConnection sendSynchronousRequest:request returningResponse:&requestResponse error:nil];
NSString *requestReply = [[NSString alloc] initWithBytes:[requestHandler bytes] length:[requestHandler length] encoding:NSASCIIStringEncoding];
NSLog(#"requestReply: %#", requestReply);
or
-(void)update{
NSString *urlAsString = [NSString stringWithFormat:#"http://YourURL.com/FakeURL/PARAMETERS"];
NSURL *url = [[NSURL alloc] initWithString:urlAsString];
self.responseData = [NSMutableData data];
NSURLRequest *request = [NSURLRequest requestWithURL:
url];
[[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(#"didReceiveResponse");
[self.responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"didFailWithError");
NSString *errorDisplay = [NSString stringWithFormat:#"Connection failed: %#", [error description]];
NSLog(#"%#",errorDisplay);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(#"connectionDidFinishLoading");
NSLog(#"Succeeded! Received %d bytes of data",[self.responseData length]);
// convert to JSON
NSError *myError = nil;
NSDictionary *res = [NSJSONSerialization JSONObjectWithData:self.responseData options:NSJSONReadingMutableLeaves error:&myError];
}
Or i should use Asynchronous Method
-(void)updateCheckList{
self.checkListresponseData = [NSMutableData data] ;
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:#"http://localhost:8080/outing-service-web/checkList/all"]];//asynchronous call
checkListConn = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(#"didReceiveResponse");
[self.checkListresponseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[self.checkListresponseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(#"didFailWithError");
NSString *errorDisplay = [NSString stringWithFormat:#"Connection failed: %#", [error description]];
NSLog(#"%#",errorDisplay);
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Cannot connect to server" delegate:nil cancelButtonTitle:nil otherButtonTitles: #"Retry",#"Close",nil];
[alertView show];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
if (connection == checkListConn) {
NSLog(#"connectionDidFinishLoading");
NSLog(#"Succeeded! Received %d bytes of data",[self.checkListresponseData length]);
// convert to JSON
NSError *myError = nil;
NSArray *res = [NSJSONSerialization JSONObjectWithData:self.checkListresponseData options:NSJSONReadingMutableLeaves error:&myError];
}
}
If you do it asynchronously, then the process will be done in the background.
In short, synchronous requests block the execution of code which creates "freezing" on the screen and an unresponsive user experience.
Check the following URL, it might get you more clear idea.
Synchronous and Asynchronous Requests

Passing param in URL to get json back in IOS

Sorry i am really beginner in IPhone development,i am pulling json data from URL and its pulling and loading data perfectly in UITableView, below is code
- (void)fetchFeed
{
NSString *requestString = #"http://bookapi.bignerdranch.com/courses.json";
NSURL *url = [NSURL URLWithString:requestString];
NSURLRequest *req = [NSURLRequest requestWithURL:url];
self.session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask =
[self.session dataTaskWithRequest:req
completionHandler:
^(NSData *data, NSURLResponse *response, NSError *error) {
NSDictionary *jsonObject = [NSJSONSerialization JSONObjectWithData:data
options:0
error:nil];
self.courses = jsonObject[#"courses"];
dispatch_async(dispatch_get_main_queue(), ^{
[self.tableView reloadData];
});
}];
[dataTask resume];
}
Now i want to add filter by instructors, Can any one tell me how i can do that.
Thanks
GET
GET request is just a matter of appending query strings to the API url, for example:
NSString *format = [NSString stringWithFormat:#"http://www.yourapiurl.com?id=%#","123";
NSURL *url = [NSURL URLWithString:format];
NSLog(#"%#",url);
//Creating the data object that will hold the content of the URL
NSData *jsonData = [NSData dataWithContentsOfURL:url];
NSError *error = nil;
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableContainers error:&error];
POST
-(NSData *)post:(NSString *)postParams{
//Build the Request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:#"http://www.yourapiurl.com"]];
[request setHTTPMethod:#"POST"];
[request setValue:[NSString stringWithFormat:#"%lu", (unsigned long)[postParams length]] forHTTPHeaderField:#"Content-length"];
[request setHTTPBody:[postParams dataUsingEncoding:NSUTF8StringEncoding]];
//Send the Request
NSData *returnData = [NSURLConnection sendSynchronousRequest: request returningResponse: nil error: nil];
//Get the Result of Request
NSString *response = [[NSString alloc] initWithBytes:[returnData bytes] length:[returnData length] encoding:NSUTF8StringEncoding];
return returnData;
}
usage:
NSString *postString = [NSString stringWithFormat:#"prop1=%#&prop2=%#&prop3=%#",
"value1","value2","value3"];
NSData *JsonData = [self post :postString];
NSDictionary *result = [NSJSONSerialization JSONObjectWithData:JsonData options:NSJSONReadingMutableContainers error:nil];
//then parse the JSON

How do I POST JSON data object to server in iOS5?

I want to send a new object created on iOS to a receiving server with a POST method using JSON data type. From what I know about receiving data from the server in iOS, is that all JSON handling was simplified by Apple with the introduction of iOS 5. But in contradistinction to GETting JSON objects, POSTing those isn't really described anywhere I could find ...
The first steps I took to try and solve the problem looked as follows:
//build an info object and convert to json
NSDictionary *newDatasetInfo = [NSDictionary dictionaryWithObjectsAndKeys:name, #"name", language, #"language", nil];
//convert object to data
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:newDatasetInfo options:kNilOptions error:&error];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:someURLSetBefore];
[request setHTTPMethod:#"POST"];
// any other things to set in request? or working this way?
[[NSURLConnection alloc] initWithRequest:request delegate:self];
// What to do with NSURLConnection? Or how to send differently?
But I really don't know how to send a JSON object to a server using a POST method at all.
Could anybody please help me out?
I worked it out by trying a bit around, here's my code:
//build an info object and convert to json
NSDictionary *newDatasetInfo = [NSDictionary dictionaryWithObjectsAndKeys:name, #"name", language, #"language", nil];
//convert object to data
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:newDatasetInfo options:kNilOptions error:&error];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:someURLSetBefore];
[request setHTTPMethod:#"POST"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPBody:jsonData];
// print json:
NSLog(#"JSON summary: %#", [[NSString alloc] initWithData:jsonData
encoding:NSUTF8StringEncoding]);
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
[connection start];
- (IBAction)txtFetchData2:(id)sender {
NSString *queryString = [NSString stringWithFormat:#"http://example.com/username.php?name=%#", [self.txtName text]];
NSMutableURLRequest *theRequest=[NSMutableURLRequest
requestWithURL:[NSURL URLWithString:
queryString]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
NSDictionary* jsonDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
#"Value1", #"Key1",
#"Value2", #"Key2",
nil];
NSError *error;
NSData* jsonData = [NSJSONSerialization dataWithJSONObject:jsonDictionary
options:NSJSONWritingPrettyPrinted error:&error];
[theRequest setHTTPMethod:#"POST"];
[theRequest addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
// should check for and handle errors here but we aren't
[theRequest setHTTPBody:jsonData];
[NSURLConnection sendAsynchronousRequest:theRequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if (error) {
//do something with error
} else {
NSString *responseText = [[NSString alloc] initWithData:data encoding: NSASCIIStringEncoding];
NSLog(#"Response: %#", responseText);
NSString *newLineStr = #"\n";
responseText = [responseText stringByReplacingOccurrencesOfString:#"<br />" withString:newLineStr];
[self.lblData setText:responseText];
}
}];
}
NSString *strUrl = #"URL";
NSURL *url = [NSURL URLWithString:strUrl];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60.0];
// For set postdata in string
NSString *strPatientID = [NSString stringWithFormat:#"%#%#%#%#",self.txtDegit1.text,self.txtDegit2.text,self.txtDegit3.text,self.txtDegit4.text];
NSString *deviceToken = #"";
postString = [NSString stringWithFormat:#"practiceid=%#&email=%#&password=%#&devicetoken=%#",strPatientID,self.txtUsername.text,self.txtPassword.text,deviceToken];
NSMutableData *httpDataBody = [NSMutableData data];
[httpDataBody appendData:[postString dataUsingEncoding:NSUTF8StringEncoding]];
NSString *strPostLength = [NSString stringWithFormat:#"%lu",[httpDataBody length]];
if ([httpDataBody length ] > 0){
[request addValue:#"application/x-www-form-urlencoded charset=utf-8" forHTTPHeaderField:#"Content-Type"];
[request setHTTPMethod:#"POST"];
[request addValue:strPostLength forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:httpDataBody];
}
urlConnection = [[NSURLConnection alloc]initWithRequest:request delegate:self];
[urlConnection start];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:[NSString stringWithFormat:#"http://webstar52.com/demo/webcommunity/work.php"]]];
NSString *post = [NSString stringWithFormat:#"&tag=%#&user_id=%#",#"getcontact",#"10408"];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSString *postLength = [NSString stringWithFormat:#"%d",[postData length]];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Current-Type"];
[request setHTTPBody:postData];
conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];

Upload HTML file to web server in iOS

I need to be able to upload an HTML file that is generated via my iPhone app, to my web server.
I am sure this is possible, however how would I do this?
Here is some code to upload a picture with iOS. It should be simple to change the file type to upload and make it work with HTML files.
NSString *urlString = #"http://yourserver.com/upload.php";
NSString *filename = #"filename";
request= [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:urlString]];
[request setHTTPMethod:#"POST"];
NSString *boundary = #"---------------------------14737809831466499882746641449";
NSString *contentType = [NSString stringWithFormat:#"multipart/form-data; boundary=%#",boundary];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
NSMutableData *postbody = [NSMutableData data];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithFormat:#"Content-Disposition: form-data; name=\"userfile\"; filename=\"%#.jpg\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[[NSString stringWithString:#"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postbody appendData:[NSData dataWithData:YOUR_NSDATA_HERE]];
[postbody appendData:[[NSString stringWithFormat:#"\r\n--%#--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[request setHTTPBody:postbody];
NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
NSLog(#"%#", returnString);
Taken from this earlier thread.