原本已經很懶得記錄這篇,會記錄這篇是因為自以為已經用的很熟了,沒想到還是出了問題,昨天花了快3個小時才搞定,雖然事後發現非戰之罪,但是還是分享一下,也讓大家可以少走一點冤望路。
1.首先,你必須有一個 Google 帳號
2.使用Google帳號登入 Google Developer Console 這裡
3.在Google Developer Console建立一個新專案,以下是最新版本的Google Developer Console的操作介面。
4.專案建立成功後,點選「啟用與管理API」
5.在這個頁面可以看到目前Google所開放的API,你可以點進去啟用您需要的API,須注意的是,沒有啟用對應的API是無法要求授權的。
6.啟用完畢後,點選右側選單的「憑證」,準備要申請存取 API 的 key 拉。
7.這邊會分成正常狀況下應該申請的,與非正常狀況下所申請通過的方法。
7.1.正常狀況下是在 API金鑰(API Key) 下
申請 iOS所使用的金鑰,接著在 OAuth 2.0 用戶端 ID 下,申請一個 iOS 裝置所使用的用戶端 ID,這個方式在我之前開發的APP中都運作正常。
所以我申請了一個 iOS 金鑰1 和 一個 iOS用戶端1,然後在上圖列表的後方,會顯示金鑰與用戶端ID,是一連串的英數字亂碼。
7.2.不正常狀況下,
直接點選新增憑證 -> OAuth 2.0 用戶端 ID -> 選擇新增其他用戶端,而不是 iOS用戶端。
建立完成後,就會顯示對應的用戶端ID與API Key
8.將 Key 與用戶端ID加入程式中,因為我用的並不是 Google 最新提供的登入方式(現在似乎比較簡單,可以使用Sign in button的方式?)。所以提供 Goolgle 的 SDK 放在 github 上面 這裡
9. 以下附上登入的程式碼,Objective-C寫的,[config xxxx]都是自己定義的config資料。說明一下其中參數
9.1.GetGoogleAuthScope會回傳一組用空格分隔的字串,用來要求Google API的權限,像是下方會要求YouTube權限、Google Drive權限、使用者Email等。
@"https://www.googleapis.com/auth/youtube https://www.googleapis.com/auth/drive.file https://www.googleapis.com/auth/userinfo.email
9.2.GetGoogleClientId,回傳的是(7)所申請的Client iD (用戶端ID)。
9.3.GetGoogleClientSecret,回傳的是(7)所申請的API Key(金鑰)。
9.4.getGoogleLoginKeychainName,回傳一個字串,用來表示你的 keychain name,可以隨意命名,自己分的出來就好。
-(void)goGoogleLoginPage{
GTMOAuth2ViewControllerTouch *viewController;
viewController = [[GTMOAuth2ViewControllerTouch alloc]
initWithScope:[config GetGoogleAuthScope]
clientID:[config GetGoogleClientId]
clientSecret:[config GetGoogleClientSecret]
keychainItemName:[config getGoogleLoginKeychainName]
delegate:self
finishedSelector:@selector(viewController:finishedWithAuth:error:)];
NSString *html = [NSString stringWithFormat:@"<html><body bgcolor=white><div align=center style='margin-top:50px;'>%@</div></body></html>", NSLocalizedStringFromTable(@"正在進入Google登入頁面...", @"InfoPlist", nil)];
viewController.initialHTMLString = html;
UINavigationController *googleLoginNavigationController = [[UINavigationController alloc]initWithRootViewController:viewController];
[self presentViewController:googleLoginNavigationController animated:YES completion:nil];
}
- (void)viewController:(GTMOAuth2ViewControllerTouch *)viewController
finishedWithAuth:(GTMOAuth2Authentication *)auth
error:(NSError *)error {
NSLog(@"error = %@", error);
if (error != nil) {
// Authentication failed
} else {
}
}
-(GTMOAuth2Authentication*)getGoogleAuth{
return [GTMOAuth2ViewControllerTouch
authForGoogleFromKeychainForName:[config getGoogleLoginKeychainName]
clientID:[config GetGoogleClientId]
clientSecret:[config GetGoogleClientSecret]];
}
10.可以透過下列方法,判斷是否處於 Google登入的狀態
-(BOOL)checkGoogleToken{
NSLog(@"[self getGoogleAuth] = %@", [self getGoogleAuth]);
if ([self getGoogleAuth] == nil || ![self getGoogleAuth].canAuthorize) {
return NO;
}else{
return YES;
}
}
11.最後,呼叫 goGoogleLoginPage 就會跳出 Google 登入的頁面,讓使用者驗證。