How can I migrate in AFNetworking 3.0?

送分小仙女□ 提交于 2020-01-04 02:22:25

问题


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" : "sldjlkasd@sjdhflksdf.com",
  "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.


回答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) {

}];



回答2:


You can check the official migration guide here




回答3:


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.




回答4:


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


来源:https://stackoverflow.com/questions/35971828/how-can-i-migrate-in-afnetworking-3-0

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!