2013-02-06 5 views
1

저는 Restkit을 시작하면서 Rk 0.20이 출시 될 예정이며 문서 및 데모는 한 걸음 뒤로 물러나 있습니다. 웹상의 대부분의 자료는 RK 0.10에 해당하며 0.20 버전에는 큰 변화가 있습니다.Restkit 0.20 기본 작업

새로운 버전이 출시 될 때 이전 버전으로 되돌리고 싶지 않습니다.

나는 간단한 데이터 그램 반환하는 URL "test.myserver.com"에서 JSON 자원이 - { "id_user": "4401", "datalocation": "4401", "나라를" "위대한 - 영국", "데이터": "testdata로" "로그인": "프레드 Bloggs에" "비밀번호": "579c0cb0ed2dc25db121283f7a98cc71" "ACCESSLEVEL": "2", "타임 스탬프": "1012 " "datahash ":"2749da29f20ce7a85092323f193adee8 " }

내가 매핑 등의 정렬이 확신하지만 내 서비스 R 인증에 동등하므로 요청에 사용자 이름과 암호를 서버에 전달해야합니다.

나는 이것을 가지고 지금까지

서버에 접속하는 것처럼 보이지만 불가피

restkit.network:RKObjectRequestOperation.m:296 개체 요청이 실패 다음과 같은 오류를 기록

NSURL *url = [NSURL URLWithString:@"http://test.myserver.com"]; 
NSURLRequest *request = [NSURLRequest requestWithURL:url]; 
RKObjectRequestOperation *objectRequestOperation = [[RKObjectRequestOperation alloc] initWithRequest:request responseDescriptors:@[ responseDescriptor ]]; 

[objectRequestOperation setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) { 
RKLogInfo(@"Load collection of Articles: %@", mappingResult.array); 
} failure:^(RKObjectRequestOperation *operation, NSError *error) { 
RKLogError(@"Operation failed with error: %@", error); 
}]; 

     [objectRequestOperation start]; 

: 근본적인 HTTP 요청 작업을 Error Domain = org.restkit.RestKit.ErrorDomain Code = -1011 "(200-299)의 예상 상태 코드에 401이 있습니다."UserInfo = 0x7884030 {NSLocalizedRecoverySuggestion = { "오류": { "code": 401, "message": "Unauthorized : Authentication re quired " } }, AFNetworkingOperationFailingURLRequestErrorKey = HTTP :에 //elancovision.umfundi.com>, NSErrorFailingURLKey = http://elancovision.umfundi.com, NSLocalizedDescription = 예상 상태 코드 (200-299) 물론 (401), AFNetworkingOperationFailingURLResponseErrorKey =}

질문 있어요 요청에 사용자 이름과 암호를 추가하는 방법입니다.

멍청한 질문에 대해 죄송합니다.

+0

API 인증에 사용되는 프로토콜을 알아야합니다.질문에 정확하게 대답 해 주시겠습니까? RESTKit은 네트워크 계층에 대해 AFNetworking을 사용합니다. 따라서 인증에 관한 한이 라이브러리를 다루어야합니다. –

+0

나는 서버 측이 restler 라이브러리를 사용하여 PHP로 작성되었다는 것을 말할 수있다. – nimbusgb

+0

'BasicAuthenticaton'사용 – nimbusgb

답변

6

기본 HTTP 인증을 사용하면 요청마다 HTTP 요청 인증 헤더 필드에 사용자 이름과 비밀번호를 삽입해야합니다.

먼저 RKObjectManager를 사용하여 요청 및 매핑의 구성을 중앙 집중화하는 것이 좋습니다. http://restkit.org/api/latest/Classes/RKObjectManager.html RKObjectManager는 (AFNetworking Library를 통해) 네트워크 매개 변수를 저장 한 다음 사용자 이름/암호, 경로, 객체 매핑을 기반으로 적절한 http 쿼리를 작성할 수 있습니다.

+0

감사합니다. 나는 당신이 게시 한 것과 똑같은 무차별 대결로 거의 똑같은 대답에 도착했다! 위키가 힌트를 주었고 버전 0.10에서 여전히 정면으로 초점을 맞추고 버전 0.2로 변경되는 사항이 중요하다는 의견을 말합니다. 바로 ..... 내 다음 도전 과제에 대해, 이제 나는 서버에서 얻을 수있는 정보를 어떻게 사용 하는가! :) – nimbusgb

+0

+1 [objectManager.HTTPClient setAuthorizationHeaderWithUsername : @ "username"password : @ "password"]; - setDefaultHeader를 사용하여 사용자 이름/비밀번호를 개별적으로 설정하려고 시도했지만 작동하지 않았습니다. 당신의 제안이있었습니다. –

1

내 솔루션 : 인증 작품의 RESTKit 위키에서보고있는 것은 올바른 매핑을 구축하는 당신에게 다음 힌트를 제공해야하는 경우

NSURL* url = [[NSURL alloc]initWithString:@"http://test.myserver.com"]; 
RKObjectManager* objectManager = [RKObjectManager managerWithBaseURL:url]; 
[objectManager.HTTPClient setAuthorizationHeaderWithUsername:@"username" password:@"password"]; 

//NSURLRequest *request = [NSURLRequest requestWithURL:url]; 
NSURLRequest *request = [objectManager requestWithObject:nil method:RKRequestMethodGET path:@"/yourAPI/yourmethod" parameters:nil]; 

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

[objectRequestOperation setCompletionBlockWithSuccess:^(RKObjectRequestOperation *operation, RKMappingResult *mappingResult) { 
     RKLogInfo(@"Load collection of Articles: %@", mappingResult.array); 
    } failure:^(RKObjectRequestOperation *operation, NSError *error) { 
     RKLogError(@"Operation failed with error: %@", error); 
    }]; 

[objectRequestOperation start]; 

:

귀하의 예를 적응, 그것은 뭔가를 줄 것이다 여기 :

// Build a RestKit manager object to look after the restful stuff 
RKObjectManager *manager = [RKObjectManager managerWithBaseURL:[NSURL URLWithString:@"http://test.myserver.com"]];; 

// Hash the GUI input password string and pass the username in plain text 
NSString *md5PW = [umfundiCommon md5:passwordField.text];   
[manager.HTTPClient setAuthorizationHeaderWithUsername:userField.text password:md5PW]; 

RKObjectMapping *WebResponse = [RKObjectMapping mappingForClass:[WSObject class]]; 

     [WebResponse addAttributeMappingsFromDictionary:@{@"id_user":@"id_user", @"datalocation": @"datalocation", @"country":@"country", @"data": @"data", @"login": @"login", @"password": @"password", @"accessLevel": @"accessLevel", @"timestamp": @"timestamp", @"datahash": @"datahash"}]; 

RKResponseDescriptor *responseDescriptor = [RKResponseDescriptor responseDescriptorWithMapping:WebResponse pathPattern:nil keyPath:nil statusCodes:RKStatusCodeIndexSetForClass(RKStatusCodeClassSuccessful)]; 
// Add the above response descriptor to the manager 
[manager addResponseDescriptor:responseDescriptor]; 

// the getObject makes the call using the stuff assembled into the manager Object and drops into either the success or the failure routines. 
[manager getObject:nil path:@"" parameters:nil success:^(RKObjectRequestOperation *operation, RKMappingResult *result) 
{ 
NSLog (@"Server WS call success:"); 

NSArray *theresults = [result array];    
for (WSObject *item in theresults) { 
    NSLog(@"datahash=%@",item.datahash); 
    NSLog(@"user_id=%@",item.id_user); 
    } 
} failure:^(RKObjectRequestOperation * operation, NSError * error) 
    { 
    NSLog (@"Server WS call failure: operation: %@ \n\nerror: %@", operation, error); 
    }]; 

........ 
관련 문제