SilverHood
SilverHood

Reputation: 723

AFNetworking 3.0 Post Issues

I need the pros here to enlighten me on what's wrong with my code. I'm trying to migrate from 2.x to 3.x and I'm getting a migraine.

 AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSDictionary *parameters = @{@"email": email, @"password": password};
[manager POST:urlString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
    NSData *jsonData = [responseStr dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:jsonData
                                                         options:0
                                                           error:nil];
    if ([[json objectForKey:@"success"] intValue] != 1) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"" message:self.error_login delegate:nil cancelButtonTitle:self.continueButton otherButtonTitles:nil];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [alert show];
    } else {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        AccountViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"account"];
        NSMutableArray *viewControllers = [NSMutableArray arrayWithArray:[[self navigationController] viewControllers]];
        [viewControllers removeLastObject];
        [viewControllers addObject:vc];
        [[self navigationController] setViewControllers:viewControllers animated:NO];
    }
} failure:^(NSURLSessionDataTask *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

The server side keeps showing that the parameters are empty.

Any guidance would be greatly appreciated =D

Upvotes: 0

Views: 446

Answers (2)

Anand Nanavaty
Anand Nanavaty

Reputation: 564

AFNetworking 3.0 Post Method code. Note :- Put this line in .h file.

+ (void)requestPostUrl: (NSString *)serviceName parameters:(NSDictionary *)dictParams success:(void (^)(NSDictionary *responce))success failure:(void (^)(NSError *error))failure;

Note :- Put this code in .m file.

+ (void)requestPostUrl: (NSString *)serviceName parameters:(NSDictionary *)dictParams success:(void (^)(NSDictionary *responce))success failure:(void (^)(NSError *error))failure {

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
[manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[manager.requestSerializer setQueryStringSerializationWithBlock:^NSString * _Nonnull(NSURLRequest * _Nonnull request, id  _Nonnull parameters, NSError * _Nullable __autoreleasing * _Nullable error) {

    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:parameters options:NSJSONWritingPrettyPrinted error:error];
    NSString *argString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return argString;
}];
//here 'kBaseURL' is Web services base URL and servicesName is Web Services API name, You have to pass from declaration side.
NSString *strService = [NSString stringWithFormat:@"%@%@",kBaseURL,serviceName];
[manager setResponseSerializer:[AFHTTPResponseSerializer serializer]];
//[SVProgressHUD showWithStatus:@"Please wait..."];
[SVProgressHUD show];
[manager POST:strService parameters:dictParams progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {


    if([responseObject isKindOfClass:[NSDictionary class]]) {

        if(success) {
            [SVProgressHUD dismiss];
            success(responseObject);
        }
    }
    else
    {
        NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        if(success) {
            [SVProgressHUD dismiss];
            NSLog(@"POST Response  : %@",response);
            success(response);
        }
    }
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

    if(failure) {
        [SVProgressHUD dismiss];
        failure(error);
    }
}];
}

Upvotes: 0

André Slotta
André Slotta

Reputation: 14040

the code for creating the post request is correct. tried it on my own server and it works as expected. so check that the values in email and password are not nil and also check your server code.

you can use a AFJSONSerializer to make your completion code a little easier though. then you do not have to convert the responseObject yourself since AFNetworking takes care of this:

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
NSDictionary *parameters = @{@"email": email, @"password": password};
[manager POST:urlString parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    NSDictionary *json = responseObject;

    if ([[json objectForKey:@"success"] intValue] != 1) {
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"" message:self.error_login delegate:nil cancelButtonTitle:self.continueButton otherButtonTitles:nil];
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [alert show];
    } else {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        AccountViewController *vc = [self.storyboard instantiateViewControllerWithIdentifier:@"account"];
        NSMutableArray *viewControllers = [NSMutableArray arrayWithArray:[[self navigationController] viewControllers]];
        [viewControllers removeLastObject];
        [viewControllers addObject:vc];
        [[self navigationController] setViewControllers:viewControllers animated:NO];
    }
} failure:^(NSURLSessionDataTask *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

Upvotes: 0

Related Questions