AFHTTPSessionManager post request - nsurlsessiondatatask

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

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

how to post data in ios objective c using NSURLSESSION AND NSJSONSerialization?

I want data in json format,
example :-
[{
name : one;
},
{
name : two;
}];
you need to post data in NSmutableURL Request. I will Provide Source code to you, Hope it will work for You.
NSString *strurl=[[NSString alloc]initWithFormat:#"%#insert_comment.php",BASE_URL];
NSString *post = [NSString stringWithFormat:#"tip_id=%#&user_id=%#&comment=%#",[self.SeletedTipData objectForKey:#"id"],[userinfo objectForKey:#"id"],CommentTextFiled.text];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strurl]];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
if (postData == nil){
UIAlertView *invalidLogin = [[UIAlertView alloc]initWithTitle:#"Alert" message:#"Something Wrong" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[invalidLogin show];
}
else{
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
/*specify the request type */
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
/* set the data to be posted on server into body for "POST"*/
[request setHTTPBody:postData];
NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[[session dataTaskWithRequest:request completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
NSMutableDictionary *dataResponse = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
NSLog(#"dataResponds=%#",dataResponse);
dispatch_async(dispatch_get_main_queue(), ^{
if ([[dataResponse objectForKey:#"status"] isEqualToString:#"true"]) {
NSLog(#"dataResponds=%#",dataResponse);
}else if ([[dataResponse objectForKey:#"status"] isEqualToString:#"false"]){
[CommanFunction displayAlertView:#"Something Wrong"];
}
});
}] resume];
}
i sure this source code will help you.

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

Sending params with POST Req in JSON with AFNetworking

I have a small problem with AFNetworking.
I'm not able to send the parameters and the data to my server (php-Skript)
The data (from NSDictionary) have to be JSON.
Ignore the senseless code parts please.
I'm receiving Errors like:
NSLocalizedDescription=Request failed: unacceptable content-type: text/html}
or Error: Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: text/html"
NSDictionary *parameter = [[NSDictionary alloc]init];
parameter = #{#"device-id": #"iOSDeveloper1234567432",#"system": #1,#"token": #"iOS-TestToken",#"mail_enabled": #"false",#"mail": #"NULL", #"movies": #[#"matrix", #"matrix2", #"matrix3"]};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameter options:0 error:nil];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
NSURL *url = [NSURL URLWithString: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 *stringkey;
stringkey = (#"k=");
stringkey = [stringkey stringByAppendingString:APIKEY];
NSString *strings;
NSString *myString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
myString = [myString stringByAppendingString:(#"&k=")];
myString = [myString stringByAppendingString:APIKEY];
NSLog(#"%#",myString);
myString = [myString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
request.HTTPBody = [myString dataUsingEncoding:NSSymbolStringEncoding];
NSData *postData = [NSJSONSerialization dataWithJSONObject:parameter options:0 error:&error];
NSLog(#"%#",error.localizedDescription);
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager GET:URL parameters:myString progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];

Send a POST request 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];