2014-06-05 105 views
1

我有一個iOS應用程序,通過OAuth 2.0與Google Plus API進行身份驗證。我遇到的問題是,即使我完全按照Google文檔進行操作,但仍無法發佈自己的時刻。這裏是我的POST請求:無法插入時刻 - Google Plus API

NSString *gp_moment = [NSString stringWithFormat:@"https://www.googleapis.com/plus/v1/people/me/moments/vault?access_token=%@", token_gplus]; 
     NSString *urlString = gp_moment; 

     NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
     [request setURL:[NSURL URLWithString:urlString]]; 
     [request setHTTPMethod:@"POST"]; 

     // Set the header - Content-Type. 
     NSDictionary *the_header = @{@"Content-type" : @"application/json", 
            @"userId" : @"me", 
            @"collection" : @"vault", 
            @"requestvisibleactions" : @"http://schemas.google.com/AddActivity"}; 

     [request setAllHTTPHeaderFields:the_header]; 

     // Set the metadata for the GP Moment (eg: name). - request_visible_actions 

     NSDictionary *metadata = @{@"target" : @{ 
              @"id" : @"replacewithuniqueidforaddtarget", 
              @"image" : @"http://www.google.com/s2/static/images/GoogleyEyes.png", 
              @"type": @"http://schema.org/CreativeWork", 
              @"description" : @"test_desc", 
              @"name" : @"TESTNAME", 
              }, 
            @"type" : @"http://schemas.google.com/AddActivity"}; 

     // Convert metadata into JSON format and submit. 
     NSError *jError = nil; 
     NSData *jsonData = [NSJSONSerialization dataWithJSONObject:metadata options:NSJSONWritingPrettyPrinted error:&jError]; 
     [request setHTTPBody:jsonData]; 

     NSHTTPURLResponse *response = nil; 
     NSError *error = nil; 

     NSData *returnedData; 
     returnedData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 
     NSDictionary *headers = [response allHeaderFields]; 

     NSLog(@"DATA: %@", [[NSString alloc] initWithData:returnedData encoding:NSASCIIStringEncoding]); 
     NSLog(@"%@", headers); 
     NSLog(@"%@", response); 
     NSLog(@"%@", error); 

更新 - 如何我對使用谷歌提供的GTMOAuth2的iOS庫使用OAuth令牌

我得到令牌。它有我使用的4個主要類別:

The GTMOAuth2 Library files

這是我從類實現到我的ViewController代碼:

-(GTMOAuth2Authentication *)begin_authorization { 

// Set the token URL to the token endpoint. 
NSURL *tokenURL; 

// Set a bogus redirect URI. It won't actually be used as the redirect will 
// be intercepted by the OAuth library and handled in the app. 
NSString *redirectURI; 

GTMOAuth2Authentication *auth; 
tokenURL = [NSURL URLWithString:@"https://accounts.google.com/o/oauth2/token"]; 
redirectURI = @"http://localhost:3000/oauth/callback/"; 

    auth = [GTMOAuth2Authentication authenticationWithServiceProvider:@"GooglePlus" tokenURL:tokenURL redirectURI:redirectURI clientID:kMyClientID_gplus clientSecret:kMyClientSecret_gplus]; 
[auth setScope:@"https://www.googleapis.com/auth/plus.login"]; 

// Set the appropriate token type. 
[auth setTokenType:@"Bearer"]; 

return auth; 
} 

-(void)authorize:(NSString *)service { 
    GTMOAuth2Authentication *auth = [self begin_authorization]; 

// Prepare the Authorization URL. We will pass in the name of the service 
// that we wish to authorize with. 
NSURL *authURL; 
authURL = [NSURL URLWithString:[NSString stringWithFormat:@"https://accounts.google.com/o/oauth2/auth/"]]; 

NSString *keyname; 
keyname = [NSString stringWithFormat:@"GooglePlus"]; 

// Display the authentication view 
GTMOAuth2ViewControllerTouch *viewController; 
viewController = [[GTMOAuth2ViewControllerTouch alloc] initWithAuthentication:auth authorizationURL:authURL keychainItemName:keyname delegate:self finishedSelector:@selector(viewController:finishedWithAuth:error:)]; 

[viewController setBrowserCookiesURL:[NSURL URLWithString:@"https://accounts.google.com/o/oauth2/auth/"]]; 

// Push the authentication view to our navigation controller instance 
[[self navigationController] pushViewController:viewController animated:YES]; 
} 

-(void)viewController:(GTMOAuth2ViewControllerTouch *)viewController finishedWithAuth:(GTMOAuth2Authentication *)auth error:(NSError *)error { 

if (error != nil) { 
    // Authentication failed 
    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Authorization Failed" message:[error localizedDescription] delegate:self cancelButtonTitle:@"Dismiss" otherButtonTitles:nil]; 
    [alertView show]; 
} 

else { 
    // Authentication succeeded 
    // Assign the access token to the instance property for later use 

    account_check = auth.accessToken; 
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; 
    [defaults setObject:account_check forKey:@"gp_token"]; 
    [defaults synchronize]; 
} 
} 

在GTMOAuth2SignIn.m文件我也設置的offline_access和 「requestvisisbleactions」 參數,如下所示:

NSMutableDictionary *paramsDict = [NSMutableDictionary dictionaryWithObjectsAndKeys: 
           @"code", @"response_type", 
           clientID, @"client_id", 
           scope, @"scope", // scope may be nil 
           @"force", @"approval_prompt", 
           @"offline", @"access_type", 
           @"http://schemas.google.com/AddActivity", @"requestvisibleactions", 
           nil]; 

UPDATE - 2

我嘗試過瀏覽所有Google Plus文檔以及查看「requestvisisbleactions」和「request_visisble_actions」之間的差異,但仍然無效。有誰知道什麼是錯的?

更新 - 3 - 我仍然得到

的錯誤我一直在從谷歌加API收到此錯誤。我只是不知道爲什麼...:

{ 
"error": { 
    "errors": [ 
    { 
    "domain": "global", 
    "reason": "unauthorized", 
    "message": "Unauthorized" 
    } 
    ], 
    "code": 401, 
    "message": "Unauthorized" 
} 
} 
+1

它報告什麼錯誤? – Prisoner

+0

@Prisoner我收到錯誤「401未經授權」。但事情是,如果擺脫JSON身體或只是編輯它,我不會再遇到這個錯誤。更重要的是,我的訪問令牌全部正確設置。 – Supertecnoboff

+0

@Prisoner你知道什麼可能是錯的嗎? – Supertecnoboff

回答

4

我相信你需要使用request_visible_actions。所以你的參數可能被設置爲

NSMutableDictionary *paramsDict = [NSMutableDictionary dictionaryWithObjectsAndKeys: 
            @"code", @"response_type", 
            clientID, @"client_id", 
            scope, @"scope", // scope may be nil 
            @"force", @"approval_prompt", 
            @"offline", @"access_type", 
            @"http://schemas.google.com/AddActivity", @"request_visible_actions", 
            nil]; 
+0

剛剛嘗試過,沒有遺憾的是它仍然出現了未經授權的錯誤:(你能想到其他任何我可能做錯了/沒有做過的事情嗎? – Supertecnoboff

+0

其實這最終確實有效。還有一些我不得不改變也是如此。你的先生也將得到賞金:) – Supertecnoboff

+0

謝謝!爲了完整性,還需要什麼? – Prisoner