我使用以下方法嘗試在10秒內同步獲取OAuth訪問令牌,否則返回nil。它工作正常,但作爲一個練習,我想將我的代碼轉換爲使用信號量。使用觀察者發出信號燈信號?
的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。
如何在後一種情況下發出信號燈信號?如果我添加一個觀察者到authentication.assessToken它會被解僱嗎?
使用ReactiveCocoa!這是一個KVO和更多的驚人的圖書館。在這種情況下,信號是你的朋友。 – allprog
謝謝 - 我會試一試! 。 。順便說一句,事實證明,是的,觀察者工作得很好。 –