Post JSON Body to API com Basic HTTP Authentication usando Objective C e AFNetworking 1.0

Eu uso SFHFKeychainUtils como um pacote para acessar e armazenar dados seguros – neste caso, a senha do usuário.

NSString *username = userProvidedUsername;
NSString *password = [SFHFKeychainUtils getPasswordForUsername:username andServiceName:@"com.mydomain.myapp.credentials" error:nil];

NSDictionary *jsonRequestDictionary = @{ @"request" : @{ @"someParameter" : @"someValue" } };


NSString *baseURLString = @"http://example.com/";
AFHTTPClient *httpClient = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:baseURLString]]; //This can be re-used within a class property
[httpClient setAuthorizationHeaderWithUsername:username password:password];
httpClient
.parameterEncoding = AFJSONParameterEncoding;

NSMutableURLRequest *request = [httpClient requestWithMethod:@"POST" path:@"path/to/api" parameters:jsonRequestDictionary];
AFJSONRequestOperation *operation = [[AFJSONRequestOperation alloc] initWithRequest:request];


[operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, NSDictionary *responseObject) {
id response
= responseObject[@"response"];
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

}];

[operation start];