AFNetworking - How to make POST request

后端 未结 1 389
情深已故
情深已故 2021-01-30 15:13

EDIT 07/14

As Bill Burgess mentionned in a comment of his answer, this question is related to the version 1.3 of AFNetworking

相关标签:
1条回答
  • 2021-01-30 15:35

    You can override the default behavior of your request being used with AFNetworking to process as a POST.

    NSURLRequest *request = [client requestWithMethod:@"POST" path:path parameters:nil];
    

    This assumes you have overridden the default AFNetworking setup to use a custom client. If you aren't, I would suggest doing it. Just create a custom class to handle your network client for you.

    MyAPIClient.h

    #import <Foundation/Foundation.h>
    #import "AFHTTPClient.h"
    
    @interface MyAPIClient : AFHTTPClient
    
    +(MyAPIClient *)sharedClient;
    
    @end
    

    MyAPIClient.m

    @implementation MyAPIClient
    
    +(MyAPIClient *)sharedClient {
        static MyAPIClient *_sharedClient = nil;
        static dispatch_once_t oncePredicate;
        dispatch_once(&oncePredicate, ^{
            _sharedClient = [[self alloc] initWithBaseURL:[NSURL URLWithString:webAddress]];
        });
        return _sharedClient;
    }
    
    -(id)initWithBaseURL:(NSURL *)url {
        self = [super initWithBaseURL:url];
        if (!self) {
            return nil;
        }
        [self registerHTTPOperationClass:[AFJSONRequestOperation class]];
        [self setDefaultHeader:@"Accept" value:@"application/json"];
        self.parameterEncoding = AFJSONParameterEncoding;
    
        return self;
    
    }
    

    Then you should be able to fire off your network calls on the operation queue with no problem.

        MyAPIClient *client = [MyAPIClient sharedClient];
        [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];
        [[AFNetworkActivityIndicatorManager sharedManager] incrementActivityCount];
    
        NSString *path = [NSString stringWithFormat:@"myapipath/?value=%@", value];
        NSURLRequest *request = [client requestWithMethod:@"POST" path:path parameters:nil];
    
        AFJSONRequestOperation *operation = [AFJSONRequestOperation JSONRequestOperationWithRequest:request success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
            // code for successful return goes here
            [[AFNetworkActivityIndicatorManager sharedManager] decrementActivityCount];
    
            // do something with return data
        }failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
            // code for failed request goes here
            [[AFNetworkActivityIndicatorManager sharedManager] decrementActivityCount];
    
            // do something on failure
        }];
    
        [operation start];
    
    0 讨论(0)
提交回复
热议问题