AFNETWORKING 3.0 Post Request Fail - objective-c

I sent a request to server using AFNETWORKING 3.0 with the following parameters:
NSString *uniqueIdentifier = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
[parameters setObject:_texLoginUname.text forKey:#"ent_email"];
[parameters setObject:_textLoginPassword.text forKey:#"ent_password"];
[parameters setObject:uniqueIdentifier forKey:#"ent_device_id"];
[parameters setObject:#"2" forKey:#"eat_device_type"];
[parameters setObject:#"22" forKey:#"ent_device_token"];
Here is my code:
NSString *URL = #"http://optime.in/apps/food_truck/user_api/login";
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:#"application/json" forHTTPHeaderField:#"Content-Type"];
[manager POST:URL parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject)
{
NSLog(#"success!");
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"error: %#", error);
NSData *errorData = error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey];
NSDictionary *serializedData = [NSJSONSerialization JSONObjectWithData: errorData options:kNilOptions error:nil];
NSLog(#"val = %#",serializedData);
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error while sending POST"
message:#"Sorry, try again."
delegate:nil
cancelButtonTitle:#"Ok"
otherButtonTitles:nil];
[alertView show];
}];
And i got this error:
NSLocalizedDescription=Request failed: not found (404),
NSUnderlyingError=0x7be19ef0 {Error Domain=com.alamofire.error.serialization.response Code=-1016 "Request failed: unacceptable content-type: text/html"
UserInfo={com.alamofire.serialization.response.error.response=http://optime.in/apps/food_truck/user_api/login } { status code: 404, headers {
Connection = "Keep-Alive";
"Content-Length" = 302;
"Content-Type" = "text/html; charset=iso-8859-1";
Date = "Tue, 20 Sep 2016 08:12:20 GMT";
"Keep-Alive" = "timeout=5, max=100";
Server = "Apache/2.4.7 (Ubuntu)";
} }, NSErrorFailingURLKey=#"mylink"
, NSLocalizedDescription=Request failed: unacceptable content-type: text/html,
Kindly help me to solve this error.

you should use below Method because AFJSONRequestSerializer is not working is AFNetworking 3.0
This method can work because I use this and only method
NSString *uniqueIdentifier = [[[UIDevice currentDevice] identifierForVendor] UUIDString];
NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
[parameters setObject:_texLoginUname.text forKey:#"ent_email"];
[parameters setObject:_textLoginPassword.text forKey:#"ent_password"];
[parameters setObject:uniqueIdentifier forKey:#"ent_device_id"];
[parameters setObject:#"2" forKey:#"eat_device_type"];
[parameters setObject:#"22" forKey:#"ent_device_token"];
NSString *URL = #"http://optime.in/apps/food_truck/user_api/login";
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:url]];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json", #"text/json", #"text/javascript",#"text/html", nil];
[manager POST:URL parameters:_parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"success!");
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"error: %#", error);
}];
Hope this thing works

Related

Image upload using AFMultipartFormData AFNetworking 3.0

NSURL *URL = [NSURL URLWithString:#"some APi"];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
UIImage *myImageObj = [UIImage imageNamed:#"avatar.jpg"];
NSData *imageData= UIImagePNGRepresentation(myImageObj);
[manager POST:URL.absoluteString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData
name:#"file"
fileName:#"avatar.jpg" mimeType:#"image/jpeg"];
// etc.
} progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"Response: %#", responseObject);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"Error: %#", error);
}];
I am trying to upload image using afnetworking 3.0 but getting this error every time
Domain=com.alamofire.error.serialization.response Code=-1011 "Request
failed: internal server error (500)"
UserInfo={com.alamofire.serialization.response.error.response= { URL: Some URL } { status
code: 500, headers {
"Access-Control-Allow-Origin" = "*";
"Content-Length" = 291;
"Content-Type" = "text/html";
Date = "Thu, 26 Jan 2017 11:41:19 GMT";
Server = "Werkzeug/0.11.11 Python/2.7.12"; } },
luckily postman provide objective-C and some other languages code but with AFNetworking i used this
NSURL *URL = [NSURL URLWithString:#"your URL"];
UIImage *myImageObj = [UIImage imageNamed:#"image.jpg"];
NSData *imageData= UIImageJPEGRepresentation(myImageObj, 0.6);
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
//manager.responseSerializer=[AFJSONResponseSerializer serializer];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager.requestSerializer setValue:#"multipart/form-data" forHTTPHeaderField:#"Content-Type"];
[manager POST:URL.absoluteString parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:imageData
name:#"file"
fileName:#"image.jpg" mimeType:#"image/jpeg"];
// etc.
} progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
NSLog(#"Response: %#", responseObject);
NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"%#",string);
} failure:^(NSURLSessionDataTask *task, NSError *error) {
NSLog(#"Error: %#", error);
}];

Raw XML Post using AFHTTPSessionManager

how can I send raw XML posts to a SOAP interface using AFHTTPSessionManager? The following code is a fork from https://github.com/wymsee/cordova-HTTP/blob/master/src/ios/CordovaHttpPlugin.m#L69:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.securityPolicy = securityPolicy;
NSString *url = [command.arguments objectAtIndex:0];
NSDictionary *parameters = [command.arguments objectAtIndex:1];
NSDictionary *headers = [command.arguments objectAtIndex:2];
[self setRequestHeaders: headers forManager: manager];
CordovaHttpPlugin* __weak weakSelf = self;
manager.responseSerializer = [TextResponseSerializer serializer];
[manager POST:url parameters:parameters progress:nil success:^(NSURLSessionTask *task, id responseObject) {
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[self setResults: dictionary withTask: task];
[dictionary setObject:responseObject forKey:#"data"];
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
} failure:^(NSURLSessionTask *task, NSError *error) {
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[self setResults: dictionary withTask: task];
NSString* errResponse = [[NSString alloc] initWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding];
[dictionary setObject:errResponse forKey:#"error"];
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}];
This posts multipart/form-data to the given (soap) url. Is it possible to alter the request so that it will send text/xml with a raw body?
Thanks!
I came up with the following solution to my problem:
NSString *url = [command.arguments objectAtIndex:0];
NSData *body = [[command.arguments objectAtIndex:2] dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *headers = [command.arguments objectAtIndex:3];
CordovaHttpPlugin* __weak weakSelf = self;
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSMutableURLRequest *req = [[AFHTTPRequestSerializer serializer] requestWithMethod:#"POST" URLString:url parameters:nil error:nil];
[req setValue:#"text/xml" forHTTPHeaderField:#"Content-Type"];
[req setValue:#"text/xml" forHTTPHeaderField:#"Accept"];
[req setHTTPBody:body];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
// Append headers
for (NSString* key in headers) {
NSString *value = [headers objectForKey:key];
[req setValue:value forHTTPHeaderField:key];
}
[[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
NSDictionary *responseHeaders = [(NSHTTPURLResponse *)response allHeaderFields];
long status = (long) [(NSHTTPURLResponse *) response statusCode];
NSLog(#"Status: %ld", status);
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
[dictionary setObject:[NSNumber numberWithInteger:status] forKey:#"status"];
[dictionary setObject:responseHeaders forKey:#"headers"];
if (!error) {
NSString *responseString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"POST SUCCESS: %#", responseString);
//[self setResults: dictionary withTask: task];
[dictionary setObject:responseString forKey:#"data"];
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
} else {
//[self setResults: dictionary withTask: task];
NSString* errResponse = [[NSString alloc] initWithData:(NSData *)error.userInfo[AFNetworkingOperationFailingURLResponseDataErrorKey] encoding:NSUTF8StringEncoding];
[dictionary setObject:errResponse forKey:#"error"];
CDVPluginResult *pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsDictionary:dictionary];
[weakSelf.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}
}] resume];

PUT Request using AFNetworking 2.0

I am trying to make the following PUT request:
NSString *url = [NSString stringWithFormat:#"https://xxxx.xxxx.xxxx/%#",orderDisplayed.lineID];
NSString *token1 = [[User sharedInstance]token];
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager.requestSerializer setValue:token1 forHTTPHeaderField:#"Authorization"];
NSDictionary *params = [[NSDictionary alloc] initWithObjectsAndKeys:
[orderDisplayed.interval valueForKey:#"id"], #"prescription_interval_id",
#1,#"prescription_auto_refill",
nil];
NSLog(#"PARAMS %#" , [params objectForKey:#"prescription_interval_id"]);
[manager PUT:url parameters:params
success:^(NSURLSessionDataTask *task, id responseObject)
{
NSLog(#"SET REFILL SUCCEEDED");
}
failure:^(NSURLSessionDataTask *task, NSError *error)
{
NSLog(#"SET REFILL FAILED");
}];
}
But for the life of me cannot make it to happen. The backend needs a data to be sent as JSON, params I am passing are in a dictionary format.

POST request using AFNetworking 3.0 in xcode 8 (Objective-c)?

I'm trying to POST request using AFNetworking 3.0.
So far i did not find the exact answer for this issue. Either i don't understand or some of the code is deprecated.
Error is "dataTaskWithRequest is deprecated"
I have this two (2) textfield that need to be post into web server.
1. email
2. pw
So far it didn't work. The current code as below
#import "ViewController.h"
#import "AFNetworking.h"
#interface ViewController ()
#end
#implementation ViewController
#synthesize email,pw;
- (IBAction)sendData:(id)sender {
NSString *URLString = #"http://localhost/test.php";
NSDictionary *parameters =#{#"email" : #"pw"};
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:0 error:&error];
NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSMutableURLRequest *req = [[AFJSONRequestSerializer serializer] requestWithMethod:#"POST" URLString:URLString parameters:nil error:nil];
req.timeoutInterval= [[[NSUserDefaults standardUserDefaults] valueForKey:#"email"] longValue];
[req setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
[req setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Accept"];
[req setHTTPBody:[jsonString dataUsingEncoding:NSUTF8StringEncoding]];
[[manager dataTaskWithRequest:req completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (!error) {
NSLog(#"Reply JSON: %#", responseObject);
if ([responseObject isKindOfClass:[NSArray class]]) {
NSLog(#"Response == %#",responseObject);
}
} else {
NSLog(#"Error: %#, %#, %#", error, response, responseObject);
}
}]resume];
}
#end
NSString *URLString = #"http://localhost/test.php";
NSDictionary *parameters =#{#"email":#"pass email id" #"pw":#"pass password"};
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.responseSerializer=[AFHTTPResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue:#"application/x-www-form-urlencoded" forHTTPHeaderField:#"Content-Type"];
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:#"application/x-www-form-urlencoded"];
[manager POST:URLString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseObject
options:kNilOptions
error:&error];
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:#"Aleksi"
message:[error localizedDescription]
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *actionOk = [UIAlertAction actionWithTitle:#"Ok"
style:UIAlertActionStyleDefault
handler:nil]; //You can use a block here to handle a press on this button
[alertController addAction:actionOk];
NSLog(#"error=%#",error );
CFRunLoopStop(CFRunLoopGetCurrent());
}];
download Afnetworking 3.0 in this link https://github.com/AFNetworking/AFNetworking
try this code, i guess it will solve your issue
NSString *url = #"http://localhost/test.php";
NSDictionary* parametersDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
email, #"email",
password, #"pw",
nil
];
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
[manager.requestSerializer setValue:#"application/x-www-form-urlencoded; charset=UTF-8" forHTTPHeaderField:#"Content-Type"];
//you can change timeout value as per your requirment
[manager.requestSerializer setTimeoutInterval:60.0];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
[manager POST:url parameters:parametersDictionary progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"%#",responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"%#",error);
}];
Simply do like following way in AFNetworking 3.0 :
- (IBAction)sendData:(id)sender {
NSString *Loginurl = [NSString stringWithFormat:Your_URL_is_here];
NSDictionary *params = #{#"user_name":username.text,
#"password":password.text,
};
//here we can see parameters which is sent to server
NSLog(#"Sent parameter to server 2 : %#",params);
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingAllowFragments];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
AFSecurityPolicy* policy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeCertificate];
[policy setValidatesDomainName:NO];
[policy setAllowInvalidCertificates:YES];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json", #"text/json", #"text/javascript",#"text/html", nil];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json",#"text/html",nil];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json",#"text/plain",nil];
[manager POST:Loginurl parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {
// Here we can see response which is coming from server
NSLog(#"Response from server 2 : %#", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);
} failure:^(NSURLSessionTask *operation, NSError *error)
{
// If Error occur, then this is AlertController Appear
NSLog(#"Error: %#", error);
UIAlertController *Erroralert= [UIAlertController
alertControllerWithTitle:#" Network Connection Failed!!"
message:#"Please try again"
preferredStyle:UIAlertControllerStyleAlert];
[self presentViewController:Erroralert animated:YES completion:nil];
UIAlertAction* yesButton = [UIAlertAction
actionWithTitle:#"Ok"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action)
{
[self resignFirstResponder];
[Erroralert dismissViewControllerAnimated:YES completion:nil];
}];
[Erroralert addAction: yesButton];
}];
}

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