20

以下代码成功连接到我的 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];
4

1 回答 1

59

针对 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
}];
于 2012-09-15T18:54:45.473 回答