小编典典

使用AFNetworking和HTTP基本身份验证

json

以下代码成功连接到我的Ruby on Rails
API,并使用AFNetworking返回JSON。我需要做什么来进行编辑以传递用户名和密码,以便我的API可以使用HTTP基本身份验证?

我已经阅读了他们的文档,但是我对Objective-C和AFNetworking还是陌生的,目前还没有意义。

NSURL *url = [[NSURL alloc] initWithString:@"http://localhost:3000/tasks.json"];

NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url];

AFJSONRequestOperation *operation = [AFJSONRequestOperation
                                     JSONRequestOperationWithRequest:request
                                     success:^(NSURLRequest *request
                                     , NSHTTPURLResponse *response
                                     , id JSON) {

    self.tasks = [JSON objectForKey:@"results"];
    [self.activityIndicatorView stopAnimating];
    [self.tableView setHidden:NO];
    [self.tableView reloadData];

    NSLog(@"JSON");

} failure:^(NSURLRequest *request
                , NSHTTPURLResponse *response
                , NSError *error
                , id JSON) {
    NSLog(@"Request Failed with Error: %@, %@", error, error.userInfo);
}];

[operation start];

阅读 300

收藏
2020-07-27

共1个答案

小编典典

AFNetworking 2.x的答案已更新

对于AFNetworking 2.x:

在2.x中,它们取消了AFHTTPClient,因此您需要使用自己的类扩展AFHTTPRequestOperationManager。然后,您可以从其他代码中调用该类。例如,这是扩展AFHTTPRequestOperationManager的示例类:

SBAPIManager.h:

#import "AFHTTPRequestOperationManager.h"

@interface SBAPIManager : AFHTTPRequestOperationManager

- (void)setUsername:(NSString *)username andPassword:(NSString *)password;

+ (SBAPIManager *)sharedManager;

@end

SBAPIManager.m:

#import "SBAPIManager.h"
#import "AFNetworkActivityIndicatorManager.h"

@implementation SBAPIManager

#pragma mark - Methods

- (void)setUsername:(NSString *)username andPassword:(NSString *)password
{
    [self.requestSerializer clearAuthorizationHeader];
    [self.requestSerializer setAuthorizationHeaderFieldWithUsername:username password:password];
}

#pragma mark - Initialization

- (id)initWithBaseURL:(NSURL *)url
{
    self = [super initWithBaseURL:url];
    if(!self)
        return nil;

    self.requestSerializer = [AFJSONRequestSerializer serializer];

    [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];

    return self;
}

#pragma mark - Singleton Methods

+ (SBAPIManager *)sharedManager
{
    static dispatch_once_t pred;
    static SBAPIManager *_sharedManager = nil;

    dispatch_once(&pred, ^{ _sharedManager = [[self alloc] initWithBaseURL:[NSURL URLWithString:@"http://localhost:3000"]]; }); // You should probably make this a constant somewhere
    return _sharedManager;
}

@end

然后,在您的代码中,可以这样调用它:

[[SBAPIManager sharedManager] setUsername:yourUsernameVariableHere andPassword:yourPasswordVariableHere];

[[SBAPIManager sharedManager] GET:@"/tasks.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
    self.tasks = [responseObject objectForKey:@"results"];
    [self.activityIndicatorView stopAnimating];
    [self.tableView setHidden:NO];
    [self.tableView reloadData];

    NSLog(@"JSON");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    // error stuff here
}];

对于AFNetworking 1.x:

AFNetworking中对此的最佳实践是使用您自己的类扩展AFHTTPClient。然后,您可以从其他代码中调用该类。例如,这是扩展AFHTTPClient的示例类:

SBAPIManager.h:

#import "AFNetworking/AFHTTPClient.h"

@interface SBAPIManager : AFHTTPClient

- (void)setUsername:(NSString *)username andPassword:(NSString *)password;

+ (SBAPIManager *)sharedManager;

@end

SBAPIManager.m:

#import "SBAPIManager.h"
#import "AFJSONRequestOperation.h"
#import "AFNetworkActivityIndicatorManager.h"

@implementation SBAPIManager

#pragma mark - Methods

- (void)setUsername:(NSString *)username andPassword:(NSString *)password
{
    [self clearAuthorizationHeader];    
    [self setAuthorizationHeaderWithUsername:username password:password];
}

#pragma mark - Initialization

- (id)initWithBaseURL:(NSURL *)url
{
    self = [super initWithBaseURL:url];
    if(!self)
        return nil;

    [self registerHTTPOperationClass:[AFJSONRequestOperation class]];
    [self setDefaultHeader:@"Accept" value:@"application/json"];
    [self setParameterEncoding:AFJSONParameterEncoding];

    [[AFNetworkActivityIndicatorManager sharedManager] setEnabled:YES];

    return self;
}

#pragma mark - Singleton Methods

+ (SBAPIManager *)sharedManager
{
    static dispatch_once_t pred;
    static SBAPIManager *_sharedManager = nil;

    dispatch_once(&pred, ^{ _sharedManager = [[self alloc] initWithBaseURL:[NSURL URLWithString:@"http://localhost:3000"]]; }); // You should probably make this a constant somewhere
    return _sharedManager;
}

@end

然后,在您的代码中,可以这样调用它:

[[SBAPIManager sharedManager] setUsername:yourUsernameVariableHere andPassword:yourPasswordVariableHere];

[[SBAPIManager sharedManager] getPath:@"/tasks.json" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
    self.tasks = [responseObject objectForKey:@"results"];
    [self.activityIndicatorView stopAnimating];
    [self.tableView setHidden:NO];
    [self.tableView reloadData];

    NSLog(@"JSON");
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    // error stuff here
}];
2020-07-27