2012-12-13 83 views
7

我正在嘗試使用RestKit來調用需要基本身份驗證的端點。如何使用RestKit 0.20.0設置基本身份驗證?

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]); 
}]; 

回答

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 /等:

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

優秀,有魅力。 –

+1

ok @BrettRyan,但你沒有使用RKObjectManager,那麼你是怎麼做到的? – jturolla

+0

與我相同的評論。 objectManager如何在調用中使用? – nimbusgb