Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set basic authentication with RestKit 0.20.0?

Tags:

restkit

I'm trying to use RestKit to call an endpoint that requires basic authentication.

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]);
}];
like image 297
Brett Ryan Avatar asked Dec 13 '12 04:12

Brett Ryan


1 Answers

Using the objectmanager this would be something like:

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

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

Then, after setting the correct request/response you can use the objectmanager to do a get/post/etc:

[objectManager getObjectsAtPath:endpoint parameters:parameters success:
     ^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) {
         // do something
     }  
     failure:^(RKObjectRequestOperation *operation, NSError *error) {
         // do something
     }
];
like image 73
Kevin R Avatar answered Oct 24 '22 02:10

Kevin R