如何使用RestKit 0.20.0设置基本身份验证?

时间:2012-12-13 04:41:30

标签: restkit

我正在尝试使用RestKit来调用需要基本身份验证的端点。

RKObjectMapping *mapping = [RKObjectMapping mappingForClass:[JSNCategory class]];
[mapping addAttributeMappingsFromDictionary:@{
    @"id": @"catId",
    @"name": @"name"
}];

NSIndexSet *statusCodes = RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful);
RKResponseDescriptor *responseDescriptor
 = [RKResponseDescriptor responseDescriptorWithMapping:mapping
                                           pathPattern:@"/api/v1/categories"
                                               keyPath:nil
                                           statusCodes:statusCodes];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL
                         URLWithString:@"https://rest.example.com"]];

RKObjectRequestOperation *operation
  = [[RKObjectRequestOperation alloc] initWithRequest:request
                                  responseDescriptors:@[responseDescriptor]];

[operation setCompletionBlockWithSuccess:
^(RKObjectRequestOperation *operation, RKMappingResult *result) {
    JSNCategory *cat = [result firstObject];
    NSLog(@"Mapped the category: %@", cat);
} failure:^(RKObjectRequestOperation *operation, NSError *error) {
    NSLog(@"Failed with error: %@", [error localizedDescription]);
}];

1 个答案:

答案 0 :(得分:26)

使用objectmanager,这将是:

NSURL* url = [[NSURL alloc]initWithString:@"http://rest.url.com"];
RKObjectManager* objectManager = [RKObjectManager managerWithBaseURL:url];

[objectManager.HTTPClient setAuthorizationHeaderWithUsername:@"username" password:@"password"];

然后,在设置正确的请求/响应后,您可以使用objectmanager进行get / post / etc:

[objectManager getObjectsAtPath:endpoint parameters:parameters success:
     ^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
         // do something
     }  
     failure:^(RKObjectRequestOperation *operation, NSError *error) {
         // do something
     }
];