2

我使用以下方法嘗試在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它會被解僱嗎?

+1

使用ReactiveCocoa!這是一個KVO和更多的驚人的圖書館。在這種情況下,信號是你的朋友。 – allprog

+0

謝謝 - 我會試一試! 。 。順便說一句,事實證明,是的,觀察者工作得很好。 –

回答

3

我不熟悉GTMOAuth2庫,但authentication.accessToken是屬性,所以似乎沒有任何東西阻止它成爲KVO兼容。在所有情況下,添加觀察者都適用於您,適用於異步和同步。因此,我只考慮異步情況。

如果你想讓你的解決方案更清潔,那麼你一定要試試Reactive Cocoa

+1

是的,事實證明它工作得很好。我認爲自己是發佈時解決問題的絕大多數方式,但這些信息可能對其他人有用,因此請將它放在這裏。 。我自己學到了兩件事:a)觀察者應該同時工作,同步和異步b)退出反應可可 –

+1

@JasperBlues我一定要嘗試颱風。我剛纔在看,但現在已經準備好部署了,我非常想嘗試一下。 – allprog

+0

你的意見對我們來說真的很有價值:) –