7

我正在尝试使用 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]);
}];
4

1 回答 1

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
     }
];
于 2012-12-13T12:02:19.213 回答