How can I migrate in AFNetworking 3.0?
Asked Answered
W

4

3

I am migrating in AFNetworking 3.0. I am using AFHTTPRequestOperation in AFNetworking but it was removed in recent updates. I tried all the possible solution. Basically I need to post a JSON with Header. I convert my NSDIctionary into a JSON object then add it as string. Here is the sample JSON with Header of mine

RequestHeader={
  "lname" : "sadhsdf",
  "bday" : "2003-03-13",
  "age" : "12",
  "address" : "dsfhskdjgds",
  "gender" : "M",
  "cnumber" : "12312412",
  "fname" : "sadhsdf",
  "RequestType" : "userregistration",
  "Email" : "[email protected]",
  "status" : "dsfhskdjgds",
  "Password" : "123456"
}

RequestHeader is an NSString and the rest are NSDictionary.

How can I apply it in AFNetworking 3.0? Thank you in advance.

Wilfredwilfreda answered 13/3, 2016 at 15:4 Comment(1)
Check this link github.com/AFNetworking/AFNetworking/wiki/…Boren
G
0
NSURL *url = [NSURL URLWithString:@"https://example.com/"];

AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];

NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:

                        height, @"user[height]",

                        weight, @"user[weight]",

                        nil];

[httpClient postPath:@"/myobject" parameters:params 
success:^(AFHTTPRequestOperation *operation, id responseObject) {

    NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];

    NSLog(@"Request Successful, response '%@'", responseStr);

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    NSLog(@"[HTTPClient Error]: %@", error.localizedDescription);
}];
Gono answered 13/3, 2016 at 15:22 Comment(1)
Hi! Thank you for your answer I appreciate it so much but It seems that AFHTTPClient is also removed.Wilfredwilfreda
G
1
NSURL *URL = [NSURL URLWithString:@"http://example.com/api"];
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];

AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:URL sessionConfiguration:configuration];
manager.responseSerializer = [AFJSONResponseSerializer serializer];

NSMutableDictionary *params = [[NSMutableDictionary alloc]init];
[params setValue:@"some value" forKey:@"someKey"];

[manager POST:@"search" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
    //If you need to send image
    UIImage *image = [UIImage imageNamed:@"my_image.jpg"];
    [formData appendPartWithFileData:UIImageJPEGRepresentation(image, 0.5) name:@"Image" fileName:@"my_image.jpg" mimeType:@"image/jpeg"];

} success:^(NSURLSessionDataTask *task, id responseObject) {

} failure:^(NSURLSessionDataTask *task, NSError *error) {

}];
Gono answered 14/3, 2016 at 16:8 Comment(0)
G
0
NSURL *url = [NSURL URLWithString:@"https://example.com/"];

AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];

NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:

                        height, @"user[height]",

                        weight, @"user[weight]",

                        nil];

[httpClient postPath:@"/myobject" parameters:params 
success:^(AFHTTPRequestOperation *operation, id responseObject) {

    NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];

    NSLog(@"Request Successful, response '%@'", responseStr);

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    NSLog(@"[HTTPClient Error]: %@", error.localizedDescription);
}];
Gono answered 13/3, 2016 at 15:22 Comment(1)
Hi! Thank you for your answer I appreciate it so much but It seems that AFHTTPClient is also removed.Wilfredwilfreda
A
0

You can check the official migration guide here

Antares answered 15/3, 2016 at 8:28 Comment(0)
T
0

Use common NSObject Class for Calling WS with AFNetworking 3.0 This is my Duplicate Answer but it was Updated with AFNetworking 3.0 First make NSObject Class with any name here i am creating NSObject Class With name Webservice.h and Webservice.m

Webservice.h

@interface Webservice : NSObject

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

@end

Webservice.m your nsobject.m file is look like this.(add two functions in .m file)

#import "Webservice.h"

#define kDefaultErrorCode 12345

@implementation Webservice

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

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager setResponseSerializer:[AFHTTPResponseSerializer serializer]];

    [manager POST:strURL parameters:dictParams progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if([responseObject isKindOfClass:[NSDictionary class]]) {
            if(success) {
                success(responseObject);
            }
        }
        else {
            NSDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
            if(success) {
                success(response);
            }
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if(failure) {
            failure(error);
        }

    }];
}

@end

make sure you have to replace your dictionary key with success and message for handling of responce callback function

Use like this call this common method from any viewcontroller.m and any methods from any viewControllers. for temporary i am using viewDidLoad for calling This WS.

 - (void)viewDidLoad {
        [super viewDidLoad];

        NSDictionary *dictParam = @{@"parameter1":@"value1",@"parameter1":@"value2"};

        [Webservice requestPostUrl:@"add your webservice URL here" parameters:dictParam success:^(NSDictionary *responce) {
            //Success
            NSLog(@"responce:%@",responce);
            //do code here
        } failure:^(NSError *error) {
            //error
        }];
    }

add your Parameter, values and webservice URL in above method. you can easily use this NSObjcet Class. for more details please visit AFNetworking 3.0 or my old answear with AFNetworking 2.0.

Twayblade answered 15/3, 2016 at 11:14 Comment(2)
Thank you so much for this you saved my day!Wilfredwilfreda
@RyanEnguero Welcome.Twayblade

© 2022 - 2024 — McMap. All rights reserved.