Search code examples
iosobjective-cpostafnetworkingnsdata

How to send NSData on server through Post request using AFNetworking?


I want to send data on server using AFNetworking. I want to send NSData not json parameter. Can anyone suggest how can I send NSData on server using AFNetworking?


Solution

  • You can use this method in AFHTTPRequestOperationManager

    - (AFHTTPRequestOperation *)POST:(NSString *)URLString
                          parameters:(id)parameters
           constructingBodyWithBlock:(void (^)(id <AFMultipartFormData> formData))block
                             success:(void (^)(AFHTTPRequestOperation *operation, id responseObject))success
                             failure:(void (^)(AFHTTPRequestOperation *operation, NSError *error))failure;
    

    The way that you would use the method is:

    [self POST:@"http://myurl.com" parameters:@{} constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        // attach the NSData to `formData`
    } success:^(NSURLSessionDataTask *task, id responseObject) {
        // Handle Success
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        // Handle Error
    }];
    

    In order to attach the data you could use this method in the AFMultipartFormData protocol

    - (void)appendPartWithFormData:(NSData *)data
                              name:(NSString *)name;