casillas
casillas

Reputation: 16793

Basic Authentication with AFNetworking

I am trying to call URL and get back to json object. However, I could not able to find out where to put basic authentication in AFNetworking operation. I could able to get my JSON object using the POSTMAN as follows.

Codesnippet of AFNetworking operation:

    NSString *string = @"MYURL";
    NSURL *url = [NSURL URLWithString:string];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];

    AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
    operation.responseSerializer = [AFJSONResponseSerializer serializer];
    [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {
    int total_count = (int)[[responseObject valueForKey:@"total_count"] integerValue];
        if (total_count > 0) {
            NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:total_count];
            for (int i = 1; i <= total_count; i++) {
                NSString *key = [NSString stringWithFormat:@"%i", i];
                id object = [responseObject objectForKey:key];
                [array addObject:object];
            }
            menuArray=array;
            tableData = [NSArray arrayWithArray:array];
            [categoryTableView reloadData];
        }
        else
        {
            NSLog(@"There is no internet connection!");
        }

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

        // 4
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"There is no internet connection!"
                                                            message:[error localizedDescription]
                                                           delegate:nil
                                                  cancelButtonTitle:@"Ok"
                                                  otherButtonTitles:nil];
        [alertView show];
    }];

Here is the POSTMAN, Calling URL with Basic Authorization

POSTMAN, callingURL with Basic Authorization

Upvotes: 1

Views: 2761

Answers (1)

Sergey  Pekar
Sergey Pekar

Reputation: 8745

You need to put your authentication to headers. You can do it in this way:

//creating crequest    
NSURL *url = [NSURL URLWithString:YOUR_URL];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

//Encode username and password

NSData *plainData = [[NSString stringWithFormat:@"%@:%@", username, password] dataUsingEncoding:NSUTF8StringEncoding];
NSString *encodedUsernameAndPassword = [plainData base64EncodedStringWithOptions:0];

//set auth header
[request addValue:[NSString stringWithFormat:@"Basic %@", encodedUsernameAndPassword] forHTTPHeaderField:@"Authorization"];

// your AFNetworking code

Upvotes: 7

Related Questions