Post method using Afnetworking in Objective-C - objective-c

How to write the code to sending POST method for the below JSON format using Afnetworking.
{
Media
{
Photo : image.jpg,
UserId : 2
},
Personal
{
Name : aaa,
Age : 30
},
Education
{
College : xxx,
Course : yyy
},
}

Obviously that's not quite the actual format, but we can guess what you might have meant. Clearly, if those numeric values (the user id and age) are expected as strings, then quote then, but hopefully it illustrates what the Objective-C representation of that dictionary might look like:
NSDictionary *parameters = #{#"Media": #{#"Photo": #"image.jpg", #"UserId": #2}, #"Personal": #{#"Name": #"aaa", #"Age": #30}, #"Education": #{#"College": #"xxx", #"Course": #"yyy" }};
Then you can post it as JSON like so:
AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager POST:#"https://yoururl.com" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#"responseObject = %#", responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"error %#", error);
}];
And if your server doesn't support HTTPS, but only HTTP, then you might have to alter your Info.plist's "App Transport Security Settings" to "Allow Arbitrary Loads".

Firstly make a dictionary of params you want to send
NSDictionary *params = #{
#"contact_no":#"9898989898",
#"password":#"••••••••••"
};
Then write the following code
AFHTTPRequestOperationManager *operationManager = [AFHTTPRequestOperationManager manager];
operationManager.requestSerializer = [AFJSONRequestSerializer serializer];
operationManager.responseSerializer = [AFJSONResponseSerializer serializer];
operationManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:#"application/json", #"text/json", #"text/javascript", #"text/html", nil];
[operationManager POST:urlString parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject){
NSLog(#"%#",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error){
if (failure)
NSLog(#"%#",error.localizedDescription);
}];
You can neglect the line in which i am setting the acceptableContentTypes.
Hope this will help.

Related

How to make a json request in AFNetworking in Objective C?

I am new in xcode and have an issue for sending request to server using AFNetworking.
Following is json request:
{
"method": "loginmethod",
"credentials": {
"credentials": {
"email": "email#email.com,
"pwd": "1111111"
}
}
}
My code is following:
NSDictionary *parameters =
#{
#"method": #"loginmethod",
#"credentials":#{
#"credentials": #{
#"email": #"email#email.com",
#"pwd": #"111111",
}
}
};
AFHTTPSessionManager *sessionManager = [AFHTTPSessionManager manager];
sessionManager.requestSerializer = [AFJSONRequestSerializer serializer];
sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects: #"application/json", nil];
[sessionManager POST: #"http://xxxxx.com/service.php" parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(#" %#", responseObject);
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(#"%#", error);
}];
Server doesn't accept this json request. So response is wrong account.
I think I have a mistake in making a json request. Or what I have mistake?
I wish you advance me. Thanks.
Following is a screenshot of Postman.

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

Get plain response from AFNetworking 2.4.1

I'm sending a POST request:
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSDictionary *parameters = #{#"method": #"login", #"email":#"email", #"password":#"password"};
[manager POST:#"http://www.apiwebsite.com" parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSLog(#"JSON: %#", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
My responseObject is:
JSON: <0d0a7b22 72657370 6f6e7365 223a224f 4b222c22 30223a22 6d61696c
696e675f 6b657922 2c223122 3a226239 65653766 34643238 64333730
30666663 37393734 65376665 66626663 3136227d>
But calling the api with POSTMAN i get:
{"response":"OK", "id":"1234223123"}
How can I get the plain or JSON response to work with it?
thanks!
To get JSON object use proper serializer AFJSONResponseSerializer instead of AFHTTPResponseSerializer you uses now.
For debug purpose convert NSData to NSString
NSLog(#"JSON: %#", [[NSString alloc] initWithData: responseObject encoding:NSUTF8StringEncoding]);

Can't get HTML code AFNetworking 2.0

I tried to make GET HTTP response. I need to get the html code for the subsequent parsing, but responseObject is nil.
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[manager GET:#"http://www.example.com/" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSError *error;
HTMLParser *parser = [[HTMLParser alloc] initWithString:responseObject error:&error];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
}];
For get html code we will need to build a custom response serializer to decode the NSData response from the web server into a NSString. We will need to subclass AFHTTPResponseSerializer and implement the following method:
- (id)responseObjectForResponse:(NSURLResponse *)response
data:(NSData *)data
error:(NSError *__autoreleasing *)error
{
return [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
}
Why for example you have not use this solution below instead of subcalssing. It does the same thing, but you don't need to create additional files, just for overload one method.
So you can just add encoding your responseObjet in the block for example, and it will work as well. I am using POST in my example but it should work with GET in the same way but without parameters, but idea of the just conversation.
+ (void)makeRequestWithParams:(NSDictionary *)params
success:(OperationCompletionBlock)success
failure:(OperationCompletionBlock)failure
{
NSString *path = #"http://www.example.com/";
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFCompoundResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:#"text/html"];
[manager POST:path parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSString* encodedString = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
NSLog(#"%#", encodedString);
success(nil);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(#"Error: %#", error);
failure(nil);
}];
}