使用AFNetworking进行基本身份验证

时间:2014-12-29 18:32:38

标签: ios afnetworking

我正在尝试调用URL并返回json对象。但是,我无法找到将基本身份验证放在AFNetworking操作中的位置。我可以使用POSTMAN获取我的JSON对象,如下所示。

AFNetworking操作的代码片段:

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

这是POSTMAN,使用基本授权调用URL

POSTMAN, callingURL with Basic Authorization

1 个答案:

答案 0 :(得分:7)

您需要将身份验证置于标头中。你可以这样做:

//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