문제

작은 트위터 클라이언트를 실행하려고 노력하고 있으며 인증이 필요한 API 호출을 테스트 할 때 문제가 발생했습니다.

내 비밀번호에는 특수 문자가 있으므로 다음 코드를 사용하려고하면 작동하지 않습니다.

NSString *post = [NSString stringWithFormat:@"status=%@", [status stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
NSData *postData = [post dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES];

NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@:%@@%@/statuses/update.json", username, password, TwitterHostname]];
[request setURL:url];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

NSURLResponse *response;
NSError *error;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

Base64를 조사하고 인증을 헤더에 넣기 시작했습니다. 나는 찾았다 Dave Dribin 's 그의 Base64 구현에 게시하면 의미가있는 것 같습니다. 그러나 그것을 사용하려고 할 때 컴파일러는 OpenSSL 라이브러리를 찾을 수없는 방법에 대해 불평하기 시작했습니다. 그래서 나는 libcrypto 라이브러리에서 링크해야한다는 것을 읽었지만 iPhone에는 존재하지 않는 것 같습니다.

또한 Apple은 암호화 라이브러리를 사용하는 앱을 허용하지 않는다고 말하는 사람들을 읽었습니다.

그래서 이제 나는 좀 고착되어 혼란 스러워요. 내 앱에 기본 인증을 얻는 가장 쉬운 방법은 무엇입니까?

건배

도움이 되었습니까?

해결책

두가지. 먼저 동기/클래스 방법보다는 비동기 메소드를 사용해야합니다.

NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:req]
                                                               cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                           timeoutInterval:30.0];

// create the connection with the request
// and start loading the data
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

인증은 대의원 에서이 방법을 구현하여 관리됩니다.

- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge;

그리고 아마도 이러한 방법도 구현해야 할 것입니다.

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data;
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;

비동기 방법을 사용하면 어쨌든 더 나은 사용자 경험을 제공하는 경향이 있으므로 추가 복잡성에도 불구하고 인증을 수행 할 수있는 능력 없이도 할 가치가 있습니다.

다른 팁

직접 ASLO 작성 메인 URL에서 사용자 이름 및 비밀번호를 다운로드 할 수 있습니다. https : // username : password@yoururl.com/

우선 NSURLConnection Delegate 파일을 호출해야합니다.

  • (BOOL) 연결 : (NSURLCONNECTION *) 연결 CANAUTHENTICATEAGAINSTPROTECTIONSPACE : (NSURLPROTECTIONSPACE *) PROTECTIONSPACE

    {

    반환 예; }

그리고 호출 - (void) 연결 : (nsurlConnection *) 연결 didreceiveAuthenticationChallenge : (nsurlauthenticationchallenge *) 도전

{
if ([challenge previousFailureCount] == 0)
        {
            NSURLCredential *newCredential;

            newCredential = [NSURLCredential credentialWithUser:@"username"
                                                       password:@"password"
                                                    persistence:NSURLCredentialPersistenceForSession];
            NSLog(@"NEwCred:- %@ %@", newCredential, newCredential);
            [[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
        }
        else
        {
            [[challenge sender] cancelAuthenticationChallenge:challenge];
            NSLog (@"failed authentication");
        }
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top