Sending params with POST Req in JSON with AFNetworking - objective-c

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

Related

How to check JSON post return value

I am new to JSON and I am trying to send a post I am wondering if how can I check if I did it properly or check the return value of it. Here's what I've done
NSURL *url = [NSURL URLWithString:#"http://json.myurl.com/.....];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
#"email", #"Email",
#"password", #"FirstName",
nil];
NSError *error;
NSData *postdata = [NSJSONSerialization dataWithJSONObject:tmp options:0 error:&error];
[request setHTTPBody:postdata];
For a beginner, I would recommend using third party framework, widely used by iOS developers across the world, called AFNetworking.
By using AFNetworking, HTTP requests are simple as that:
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[manager POST:url parameters:parameters progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
// TODO: Parse success here!
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
// TODO: Parse failure here!
}];
In given example, object responseObject is a representation of API response JSON object.
Installation and further usage instructions of AFNetworking can be found in their website.
To check JSON POST return value:
NSString *strUrl=[NSString stringWithFormat:#"http://json.myurl.com/....."];
NSString *webStringURL = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url = [NSURL URLWithString:webStringURL];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSDictionary *tmp = [[NSDictionary alloc] initWithObjectsAndKeys:
#"email", #"Email",
#"password", #"FirstName",
nil];
NSError* error;
NSData* postData = [NSJSONSerialization dataWithJSONObject:tmp options:NSJSONWritingPrettyPrinted error: &error];
NSString *postLength = [NSString stringWithFormat:#"%lu", (unsigned long)[postData length]];
[request setURL:url];
[request setHTTPMethod:#"POST"];
[request setValue:postLength forHTTPHeaderField:#"Content-Length"];
[request setHTTPBody:postData];
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *jsonData, NSError *error)
{
if (!error)
{
NSDictionary *jsonResponse = [NSJSONSerialization JSONObjectWithData:jsonData options:NSJSONReadingMutableLeaves error:&error];
dispatch_async(dispatch_get_main_queue(),^
{
NSLog(#"jsonResponse--->%#",jsonResponse);
});
}
else
{
dispatch_async(dispatch_get_main_queue(),^
{
NSLog(#"error--->%#",error.description);
});
}
}];
And to check you JSON format is correct or not go through this link

POST Method With Multiple JSON Objects(Objective C)

Hello everyone I m trying to send two json objects in one request.
Here is what I did so far:
NSDictionary *credentials = [request getCredentials];
NSURL *url = [NSURL URLWithString:#"https://myurl.com"];
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
NSMutableURLRequest *req = [[NSMutableURLRequest alloc] initWithURL:url];
req.HTTPMethod = #"POST";
[req setValue:#"application/json" forHTTPHeaderField:#"Accept"];
[req setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
NSError *error = nil;
NSData *o = [NSJSONSerialization dataWithJSONObject:output
options:NSJSONWritingPrettyPrinted error:&error];
NSData *c = [NSJSONSerialization dataWithJSONObject:credentials
options:NSJSONWritingPrettyPrinted error:&error];
NSString *myString = [[NSString alloc] initWithData:o encoding:NSUTF8StringEncoding];
NSLog(#"DATA: %#",myString);
if (!error) {
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:req
fromData:c completionHandler:^(NSData *data,NSURLResponse *response,NSError *error) {
NSLog(#"RESPONSE %#", response);
}];
[uploadTask resume];
}
In this code I send only "NSData *c" but also I want to send "NSData *o" in the same request. Is it possible, I need your helps. Thanks.
you can combine dictonaries into one using below code then post to server.
#property (nonatomic, strong) NSMutableDictionary *configuration;
...
-(NSMutableDictionary*) configuration{
if (!_configuration) {
NSDictionary *core_config = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:#"installation" ofType:#"plist"]];
NSDictionary *app_config = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle bundleWithPath:#"/path/to"] pathForResource:#"something/data" ofType:#"plist"]];
[_configuration addEntriesFromDictionary: core_config];
[_configuration addEntriesFromDictionary: app_config];
NSLog(#"merged: %lu, core: %lu, app: %lu", (unsigned long)[_configuration count], (unsigned long)[core_config count], (unsigned long)[app_config count]);
// merged: 0, core: 4, app: 5
}
return _configuration;
}

Twilio SMS Parsing using objective C

I need to integrate SMS Verification using Twilio url.
I have ACCOUNT_SID,AUTH_TOKEN and url but not able to parse using Objective C.
CODE:
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
NSURLSession *session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:[NSOperationQueue mainQueue]];
NSString *post = [NSString stringWithFormat:#"From='number'To=%#&Body=message %d to verify your mobile number.",txt_otp.text,[[self sms_verification_code]intValue]];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:#"https://api.twilio.com/2010-04-01/Accounts/(SID)/SMS/Messages"]cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
NSString *authStr = [NSString stringWithFormat:#"SID:TOKEN"];
NSData *authData = [authStr dataUsingEncoding:NSUTF8StringEncoding];
[request setHTTPMethod:#"POST"];
[request setHTTPBody:[post dataUsingEncoding:NSUTF8StringEncoding]];
NSString *authValue = [NSString stringWithFormat:#"Basic %#", [authData base64EncodedStringWithOptions:0]];
[request setValue:authValue forHTTPHeaderField:#"Authorization"];
[[session dataTaskWithRequest:request
completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
if (!error) {
NSDictionary *responseDictionary = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:&error];
NSLog(#"SMS verification%#",responseDictionary);
}
}] resume];
I have succeeded parsing using AFNetworking SDK.
NSString *kTwilioSID = #"sid";
NSString *kTwilioSecret = #"token";
NSString *kFromNumber = #"";
NSString *kToNumber =#"";
NSString *kMessage = [NSString stringWithFormat:#"message %d",[[self sms_verification_code] intValue]];
NSString *urlString = [NSString
stringWithFormat:#"https://%#:%##api.twilio.com/2010-04-01/Accounts/%#/SMS/Messages/",
kTwilioSID, kTwilioSecret,kTwilioSID];
NSDictionary*
dic=#{#"From":kFromNumber,#"To":kToNumber,#"Body":kMessage};
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer=[AFHTTPResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes=[NSSet setWithObject:#"application/xml"];
[manager POST:urlString parameters:dic progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSLog(#"success %#",[[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
completion:nil];
} failure:^(NSURLSessionTask *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];

Objective c post with json data request to server

I am trying to post data to server and send data json like this
data: {"userID":"AAAAA","token":"12345","type":"BBB","version":"45"}
here is image
NSDictionary *requestDictionary = #{#"data" : #{
#"{userID" : #"AAA", #"token ": #"12345",#"type":#"iOS",#"version":#"1}"}};
NSURL *urls =[NSURL URLWithString:[NSString stringWithFormat:#"http://URL/send_code"]];
self.request = [[NSMutableURLRequest alloc]init];
[self.request setURL:urls];
NSString *contentType = [NSString stringWithFormat:
#"application/json"];
[request addValue:contentType forHTTPHeaderField: #"Content-Type"];
[request setHTTPMethod:#"POST"];
[request addValue:#"IOS" forHTTPHeaderField: #"X-Application-Platform"];
[request setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[request setHTTPBody:[NSJSONSerialization dataWithJSONObject:requestDictionary options:0 error:nil]];
NSData *postdata = [NSJSONSerialization dataWithJSONObject:requestDictionary options:0 error:nil];
urlconnection = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:true];
i ve tried several times and get invalid data response
please help me.thanks in advance
Try to send using AFNetworking:
First try to convert Json into Dictionary.
NSError *error;
NSData *objectData = [#"{Your dictionary}" dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *json = [NSJSONSerialization JSONObjectWithData:objectData
options:NSJSONReadingMutableContainers
error:&error];
Then you can send this dictionary:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[manager POST:#"your_URL" parameters:json progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"Complete");
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"Fail");
}];

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