how to create AFNetworking 3 from-data request - objective-c

MY CODE IS FOR AFNETWOKING 3.0
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"multipart/form-data"];
[manager.requestSerializer setTimeoutInterval:30];
[manager POST:URLString parameters:param progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
if([responseObject isKindOfClass:[NSDictionary class]]) {
RequestCompletionHandlerBlock(responseObject);
}
else {
NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
RequestCompletionHandlerBlock(response);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"Error Is %#",error.description);
RequestFailedHandlerBlock(#{#"error " :error.description});
}];
RESPONCE IS :
NSLocalizedDescription=Request failed: unacceptable content-type: text/html

try this
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc]initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setTimeoutInterval:30];
manager.responseSerializer.acceptableContentTypes = [manager.responseSerializer.acceptableContentTypes setByAddingObject:#"text/html"];
[manager POST: URLString parameters:param constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
} progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"all data=%#",responseObject);
}
}
failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
}];

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

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

AFHTTPSessionManager GET method syntax error?

Here's my code
AFHTTPSessionManager *manger = [[AFHTTPSessionManager alloc] init];
[manger GET:requestUrl parameters:params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
}];
I got two error from Xcode.
Unknown type name 'id'
Incompatible block pointer types sending 'void (^)(NSURLSessionDataTask * _Nonnull __strong, int)' to parameter of type 'void (^ _Nullable)(NSURLSessionDataTask * _Nonnull __strong, id _Nullable __strong)'.
Why is this happen?I had imported AFNetworking file in my header file.My Xcode version is 8.2,and AFNetworking version is 3.1.When I put this code snippet in my other project,there was no error.That was really confused me.Anyone can help?
I used Carthage to import AFNetwoking,still the same error.:(
Final solution:I recreate the project.And migrate the old code to new project.It works.But still know the reason why the old version code not work.
your method should like this
-(void)callWebserviceWithParams:(NSMutableDictionary *)_params
action:(NSString *)_action
success:(void (^)(id))_success
failure:(void (^)(NSError *))_failure
{
if ([[AFNetworkReachabilityManager sharedManager] isReachable]) {
//AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
// manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSString *url = [BASE_URL stringByAppendingString:_action];
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:_params progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"response = %#", responseObject);
if( _success )
{
_success( responseObject ) ;
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"error = %#", error);
if( _failure )
{
_failure( error) ;
}
}];
}
}

AFNetworking send array in JSON parameters of GET request

I am sending array as a parameter in AFNetworking GET Request.
My code is as follows:
- (void)getProductSearchResult:(NSString *)locale andSearchDict:(NSDictionary *)dictSearch{
NSString *strURL = [NSString stringWithFormat:#"%#/%#/search?%#",BASEURL,locale,APIFORMAT];
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager GET:strURL parameters:dictSearch success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSDictionary *jsonDict = (NSDictionary *)responseObject;
if ([jsonDict isKindOfClass:[NSDictionary class]] || [jsonDict isKindOfClass:[NSMutableDictionary class]]) {
if (self.delegate && [self.delegate respondsToSelector:#selector(API_ProductSearch_didSuccess:)]) {
[self.delegate API_ProductSearch_didSuccess:jsonDict];
}
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (self.delegate && [self.delegate respondsToSelector:#selector(api_ProductSearch_didFailWithError:)]) {
[self.delegate api_ProductSearch_didFailWithError:[NSError description]];
}
}];
}
The dictionary which I pass as parameter is as follows:
{
"brand_filter" = (
1
);
"category_filter" = (
438
);
"max_price" = "47.37188";
"min_price" = "1.95";
"price_currency" = USD;
"supplier_filter" = (
"Aakron Line"
);
}
URL which created is shown like
http://demo.aakronline.ca/app_dev.php/api/v1/en_us/search?_format=json&brand_filter[]=1&category_filter[]=438&max_price=48.04479&min_price=2.622917&price_currency=USD&supplier_filter[]=Aakron%20Line
The problem area in URL is array is not passed in proper format i.e.
brand_filter[]=1&category_filter[]=438 instead of brand_filter=[1]&category_filter=[438]
Can anyone tell me how to solve this mistake?
But I am not getting the successful response.
In afnetworking 3.0, instead of AFHTTPRequestOperationManager use AFHTTPSessionManager
NSString *strUrl = [NSString stringWithFormat:#"%#/%#/search?%#",BASEURL,locale,APIFORMAT];
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] init];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager GET:strUrl parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"value: %#",responseObject);
//other code as it is
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"Error: %#",error);
}];

AFNetworking 2.5.4 sending file with PATCH request

Using AFNetworking for communication between REST API and my application I ran into a strange behaviour wenn trying to upload an image with PATCH request.
I use following code:
- (void) uploadImage: (UIImage *)image {
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *parameters = #{};
AFHTTPRequestSerializer *requestSerializer = [manager requestSerializer];
NSError *e = nil;
NSMutableURLRequest *request = [requestSerializer multipartFormRequestWithMethod:#"PATCH"
URLString:requestString
parameters:parameters
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:UIImagePNGRepresentation(image)
name:#"image"
fileName:#"image.png"
mimeType:#"image/png"];
} error:&e];
[manager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog("OK");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog("FAILED");
}];
}
Neither success not failed block of operation will be reached.
Wenn I change the request method to POST everything works fine, but the Server accepts only PATCH method for this case.
Am I doing something wrong?
I finally found a solution for my question:
- (void)uploadImage:(UIImage *)image
withSuccess:(SomeSuccessBlock)success
failure:(SomeFailureBlock)failure {
NSString *requestString = "Some url";
NSError *e = nil;
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
AFHTTPRequestSerializer *requestSerializer = [manager requestSerializer];
NSMutableURLRequest *request = [requestSerializer multipartFormRequestWithMethod:#"POST" URLString:requestString parameters:#{}
constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileData:UIImagePNGRepresentation(image)
name:#"user[avatar]"
fileName:#"avatar.png"
mimeType:#"image/png"];
} error:&e];
if (e && failure) {
failure(e);
return;
}
[request setHTTPMethod:#"PATCH"];
[request setValue:#"PATCH" forHTTPHeaderField:#"X-HTTP-Method-Override"];
AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
if (success) {
success();
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
if (failure) {
failure(error);
}
}];
[operation start];
}