Send a POST request Objective-C - objective-c

I need to send a POST request to a website to load more results of the page (There is about 200 results that I want to parse (using TFHpple) but the page is showing just 40 and you need to click "Show More Results" at the button to load more).
I tried to search the web how to send a POST request and I tried but it hasn't succeeded :( Can anyone help me figure it out?
General information:
Remote Address:212.117.156.55:80
Request URL:http://www.d.co.il/DOTNET/ajax/GetMoreResults
Request Method:POST
Status Code:200 OK
File Name: GetMoreResults
If there is any additional information required, just write in and I'll give you it.
Thank you very much!
Am I done this right?
NSURL *url=[NSURL URLWithString:#"http://www.d.co.il/SearchResults/?query=%D7%A9%D7%95%D7%A4%D7%A8%D7%A1%D7%9C&type=tag&location="];
NSData *data=[NSData dataWithContentsOfURL:url];
TFHpple *parser=[TFHpple hppleWithHTMLData:data];
NSString *XpathQueryString=#"//p[contains(#class, \"result-contact-address\")]";
NSArray *Nodes=[parser searchWithXPathQuery:XpathQueryString];
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *postUrl = [NSURL URLWithString:#"http://www.d.co.il/DOTNET/ajax/GetMoreResults"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:postUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"GetMoreResults" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"GetMoreResults" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: #"1", #"batchNumber",
#"IOS TYPE", #"typemap",
nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
}];
[postDataTask resume];
int i=1;
for (TFHppleElement *element in Nodes) {
NSString *address = element.text;
NSLog(#"%#,%d",address,i);
i++;
}

Step 1 : You need to build a service which takes the batchNumber and feeds you data belonging to that batch. So, initially you would send batchNumber = 0 and server returns you first 40 records.
Step 2 : On UI side, return 1 count more than the count of data records you have in hand to show. That additional count is for the last cell Show More.
Step 3 : On tap on Show More, increase your current batchNumber by 1 and make the server call to get the next batch records.
Step 4 : Continue step 2 & 3 util all records are loaded.
Finally, this is how you load server data using a post request:
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"[JSON SERVER"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: #"TEST IOS", #"name",
#"IOS TYPE", #"typemap",
nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
}];
[postDataTask resume];

Related

How to fetch data using NSUrl session in objective-C?

I am trying to fetch JSON data and parse it using NSUrl session but getting null every time - Also in addition to that i want o show all data in table view
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"https://dl.dropboxusercontent.com/s/2iodh4vg0eortkl/facts.json"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"text/plain" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"text/plain" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"GET"];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: #"Value", #"Key", nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(#"Resopnse == %#",response);
if (response != nil) {
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"JSon dict === %#",jsonDict);
}
}];
[postDataTask resume];
May I know what i am doing wrong is anything other good way to do same?
Try following code.
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"https://dl.dropboxusercontent.com/s/2iodh4vg0eortkl/facts.json"]];
[request setHTTPMethod:#"GET"];
[request addValue:#"text/plain" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"text/plain" forHTTPHeaderField:#"Accept"];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *requestReply = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSData * responseData = [requestReply dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:responseData options:kNilOptions error:&error];
NSLog(#"requestReply: %#", jsonDict);
}] resume];
Please use the below code for the same. Hope it will solve your problem.
NSString *strUrl = [NSString stringWithFormat:yourUrl];
NSURL *url = [NSURL URLWithString:strUrl];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request
queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response,
NSData *data, NSError *connectionError)
{
if (data.length > 0 && connectionError == nil)
{
NSDictionary *dicResponse = [NSJSONSerialization JSONObjectWithData:data options:0 error:NULL];
NSLog(#"%#",dicResponse);
}
}];

Https Post in objective c

I have the below code for http post request,
FIRDatabaseReference *agreementCreateReference = [[[FIRDatabase database] referenceWithPath:#"/agreements/"] childByAutoId];
NSLog(#"autoId %#",agreementCreateReference.key);
NSLog(#"autoId %#",_propertyId);
NSString *post = [NSString stringWithFormat:#"agreementId=%#&listingId=%#",agreementCreateReference.key,_propertyId];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString:#"https://krib-api-onbit.herokuapp.com/api/agreements"]];
[request setHTTPMethod:#"POST"];
[request setValue:idToken forHTTPHeaderField:#"X-FIREBASE-ID-TOKEN"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:postData];
NSLog(#"%#",request);
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(#"data dtat %#",data);
}];
[dataTask resume];
This url with parameters and headers returns data in the Postman. When I use to get data using objective c using the above code I get <42616420 52657175 6573740a> as data. And not calling the backend either.
After spending hours on this issue, I just sent the parameters via the URl and it returned data and printed the request in the backend. Code is as follows for anyone.
FIRDatabaseReference *agreementCreateReference = [[[FIRDatabase database] referenceWithPath:#"/agreements/"] childByAutoId];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSString *url = [NSString stringWithFormat:#"https://krib-api-onbit.herokuapp.com/api/agreements?agreementId=%#&listingId=%#",agreementCreateReference.key,_propertyId];
[request setURL:[NSURL URLWithString:url]];
[request setHTTPMethod:#"POST"];
[request setValue:idToken forHTTPHeaderField:#"X-FIREBASE-ID-TOKEN"];
[request setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
//[request setHTTPBody:postData];
NSLog(#"%#",request);
NSURLSession *session = [NSURLSession sharedSession];
NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSLog(#"data dtat %#",data);
NSString *res = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(#"res %#",res);
}];
[dataTask resume];

How to post API through NSURLSession?

I have following code
How to parse response ?
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
NSURL *url = [NSURL URLWithString:# "API-URL"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: #"key", #"76658b01d08e43f65c6930933f69f1",
nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
}];
[postDataTask resume];
How to get dictionary output after getting response from dataTaskResponse?
Please Try the following Code.
NSError* error;
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:&error];
NSLog(#"json: %#", json);

Send POST request in Objective-C

I need to send a POST request to a website to load more results of the page (There is about 200 results that I want to parse (using TFHpple) but the page is showing just 40 and you need to click "Show More Results" at the button to load more (there is 4 pages))).
Every time one or two addresses are different and the other is the same, why is it? All of them should be different.
I tried to search the web how to send a POST request and I tried but it hasn't succeeded :( Can anyone help me figure it out?
General information:
Remote Address:212.117.156.55:80
Request URL:http://www.d.co.il/DOTNET/ajax/GetMoreResults
Request Method:POST
Status Code:200 OK
File Name: GetMoreResults
If there is any additional information required, just write in and I'll give you it.
Thank you very much!
Am I done this right?
NSURL *url=[NSURL URLWithString:#"http://www.d.co.il/SearchResults/?query=%D7%A9%D7%95%D7%A4%D7%A8%D7%A1%D7%9C&type=tag&location="];
NSData *data=[NSData dataWithContentsOfURL:url];
TFHpple *parser=[TFHpple hppleWithHTMLData:data];
NSString *XpathQueryString=#"//p[contains(#class, \"result-contact-address\")]";
NSArray *Nodes=[parser searchWithXPathQuery:XpathQueryString];
for (int i=0; i<4; i++)
{
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *postUrl = [NSURL URLWithString:#"http://www.d.co.il/DOTNET/ajax/GetMoreResults"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:postUrl
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"GetMoreResults" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"GetMoreResults" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSDictionary *mapData = [[NSDictionary alloc] initWithObjectsAndKeys: #"80", #"batchNumber",
#"IOS TYPE", #"typemap",
nil];
NSData *postData = [NSJSONSerialization dataWithJSONObject:mapData options:0 error:&error];
[request setHTTPBody:postData];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
}];
[postDataTask resume];
}
int i=1;
for (TFHppleElement *element in Nodes) {
NSString *address = element.text;
NSLog(#"%#,%d",address,i);
i++;
}

AFHTTPSessionManager post request

I want to post a request to server. It is working fine if I am using NSURLSessionDataTask. But underneath I need to use AFNetworking as my whole application is using it. But when I am trying to hit the same service in AFHTTPSessionManager with POST method, It is giving me request time out.
Below are both the codes.
NSError *error;
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:nil delegateQueue:nil];
NSURL *url = [NSURL URLWithString:#"BASE URL"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
[request addValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[request addValue:#"application/json" forHTTPHeaderField:#"Accept"];
[request setHTTPMethod:#"POST"];
NSString *postString = #"1";
NSData *data = [postString dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPBody:data];
NSURLSessionDataTask *postDataTask = [session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
}];
[postDataTask resume];
AFNetworking kit version :-
AFHTTPSessionManager *client = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:#"BASE URL"]];
NSDictionary *request = #{#"Content-Type":#"application/json",
#"Accept":#"application/json",
};
NSString *postString = #"1";
NSData *data = [postString dataUsingEncoding:NSUTF8StringEncoding];
[client POST:#"" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithHeaders:request body:data];
} success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"%#",responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"%#",error);
}];
Please help me in implementing it in right way.
I solved this problem by creating my own request and give its configuration to AFURLSessionManager and then holding my own NSURLSessionUploadTask object.
Thanks