iOS AFOAuth2Manager使用心得

來源:互聯網
上載者:User

標籤:

git地址:  https://github.com/AFNetworking/AFOAuth2Manager

 

這個庫,不多說,實現OAuth 2.0授權訪問。

確實可以減輕很大的負擔,而且使用很容易。但是,我也是遭遇了挫折好幾次才玩懂的。估計是自己太笨了。

 

 

 

 

NSURL *baseURL = [NSURL URLWithString:@"http://xxx.xxx.x.x:xxxx"];    AFHTTPRequestOperationManager *manager = [[AFHTTPRequestOperationManager alloc] initWithBaseURL:baseURL];        [manager POST:@"/OAuth/token"       parameters:@{@"client_id":@"xxx",                    @"client_secret":@"xxx",                    @"grant_type":@"xxx",                    }          success:^(AFHTTPRequestOperation *operation, id responseObject) {              NSLog(@"\n=============accessToken=================\n\n%@\n\n",responseObject);                            //! 儲存credential,內含access_token              AFOAuthCredential *credential = [[AFOAuthCredential alloc]initWithOAuthToken:[responseObject objectForKey:@"access_token"]                                                                                 tokenType:[responseObject objectForKey:@"token_type"]];              [credential setExpiration:[responseObject objectForKey:@"expires_in"]];                            //! 記錄token到期時間,這裡的token有效時間為1800s              _tokenInvalidateTime = [NSDate dateWithTimeIntervalSinceNow:1770];                            //! 設定需要在Headers中加入的參數Authorization,_opManager為另一個AFHTTPRequestOperationManager,因為我這個例子裡,二者使用的baseURL不同              _opManager.requestSerializer = [AFHTTPRequestSerializer serializer];              [_opManager.requestSerializer setAuthorizationHeaderFieldWithCredential:credential];              //! 我這裡並沒有用做著提供的方法,將credential寫入檔案,             //!  因為我是直接將Authorization的設定放在了這裡完成             //!  如果,我沒有用到這_opManager             //!  這裡我就應該用[AFOAuthCredential storeCredential:credential withIdentifier:serviceProviderIdentifier];             //!  這個方法將credential寫入檔案,             //! 之後用AFOAuthCredential *credential =        [AFOAuthCredential retrieveCredentialWithIdentifier:serviceProviderIdentifier];             //!  方法在其他地方重新擷取這個credential。credential裡就還有token等資訊          }          failure:^(AFHTTPRequestOperation *operation, NSError *error) {              NSLog(@"\nAccessToken擷取失敗: %@", error);          }]; 

 

iOS AFOAuth2Manager使用心得

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.