다음 메소드를 사용하여 10 초 이내에 OAuth 액세스 토큰을 동기식으로 얻으려고합니다. 그렇지 않으면 nil을 반환합니다. 그것은 잘 작동하지만 연습으로 세마포어를 사용하도록 코드를 변환하고 싶습니다.observer를 사용하여 세마포어에 신호를 보내시겠습니까?
Runloop 버전
- (NSString*)oAuthAccessToken
{
@synchronized (self)
{
NSString* token = nil;
_authenticationError = nil;
if (_authentication.accessToken)
{
token = [NSString stringWithFormat:@"Bearer %@", _authentication.accessToken];
}
else
{
[GTMOAuth2ViewControllerTouch authorizeFromKeychainForName:_keychainName authentication:_authentication];
[_authentication authorizeRequest:nil delegate:self didFinishSelector:@selector(authentication:request:finishedWithError:)];
for (int i = 0; i < 5; i++)
{
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1]];
if (_authentication.accessToken)
{
token = [NSString stringWithFormat:@"Bearer %@", _authentication.accessToken];
break;
}
else if (_authenticationError)
{
break;
}
}
}
// LogDebug(@"Returning token: %@", token);
return token;
}
}
세마포어 버전
코드의 세마포어 버전이가는이 같은 작은 선물 :
- (NSString*)oAuthAccessToken
{
@synchronized (self)
{
NSString* token = nil;
_authenticationError = nil;
if (_authentication.accessToken)
{
token = [NSString stringWithFormat:@"Bearer %@", _authentication.accessToken];
}
else
{
_authorizationSemaphore = dispatch_semaphore_create(0);
dispatch_async(_authorizationRequestQueue, ^(void)
{
[GTMOAuth2ViewControllerTouch authorizeFromKeychainForName:_keychainName authentication:_authentication];
[_authentication authorizeRequest:nil delegate:self didFinishSelector:@selector(authentication:request:finishedWithError:)];
});
dispatch_semaphore_wait(_authorizationSemaphore, DISPATCH_TIME_FOREVER);
if (_authentication.accessToken)
{
token = [NSString stringWithFormat:@"Bearer %@", _authentication.accessToken];
}
}
return token;
}
}
잡았다! GTMOAuth2가 다시 위임 방법을 통해 호출하는 네트워크를 공격해야하는 경우 GTMOAuth2 때때로 즉시
- 반환합니다. 이 방법에서는 세마포 신호를 보냅니다.
- 때때로 GTMOAuth2가 즉시 반환 할 수 있습니다. 문제는 메소드가 void를 반환한다는 것입니다.
후자의 경우 어떻게하면 내 세마포어에 신호를 보낼 수 있습니까? 인증 기관에 관찰자를 추가하면 토큰이 발사됩니까?
ReactiveCocoa! KVO 등을위한 놀라운 라이브러리입니다. 신호는 그런 경우에 당신의 친구입니다. – allprog
고마워요. 시험해 볼게요 !! . . Btw, 그렇습니다. 관찰자는 잘 작동합니다. –