iOS, Swift 3, Google 登入/登出教學(Sign In/Sign Out)
完整專案 : https://github.com/Jerry0420/SignInExample.git
使用模擬器建立後,選擇第1個tab,即為本篇教學的部分。
以下為官方教學文件(有swift版本):
Before you can begin integrating your iOS app with the Google Sign-In components, you must download the dependencies…developers.google.com
- 使用xcode建立新專案
2. 用cocoapods將專案匯入Google SDK
( pod init , pod ‘Google/SignIn’ , pod install )
Before you can begin integrating your iOS app with the Google Sign-In components, you must download the dependencies…developers.google.com
(照著Set up your CocoaPods dependencies的描述匯入)
3. 建立configuration file,並匯入建立的專案內
填入app名稱(可任填,但建議同剛剛建立的專案名稱,方便辨識)及已建立專案的Bundle ID,
接著點選Choose and configure services 選擇Google Sing-In後,即可建立configuration file,並將configuration file下載下來,直接拉到專案內。

4. 在Target → Info → URL Types內填入REVERSED_CLIENT_ID
(REVERSED_CLIENT_ID位於configuration file內)


在Targets -> Capabilities中,記得將keyChain Sharing打開。
在模擬器中,有時會無法登入,開啟keyChain Sharing即可解決。

5. 以上,完成環境設定,接著撰寫程式碼。
首先在AppDelegete內import GoogleSignIn 和Google Framework,並將以下程式碼加入AppDelegate內:
import GoogleSignIn
import Google
本教學欲建立登入及登出按鈕,首先實作以storyBoard的方式,接著實作以程式碼的方式,分別生成登入按鈕。
6. 首先使用AutoLayout建立登入鈕,將一個UIView拉到storyBoard內,並將autolayout拉好,將其class改為GIDSignInButton (將view設為綠色是為了方便觀察位置)

接著將這個view拉進ViewController內。
7. ViewController要遵循GIDSignInUIDelegate及GIDSignInDelegate, 同樣要import GoogleSignIn 和Google Framework。
同時,在viewDidLoad中,將delegate和uiDelegate對象設為self (不一定要在viewDidLoad中,可依程式的架構自由放置,但一定要設置delegate的對象)
8. 此時,讓程式跑看看,可進入登入頁面,輸入帳號密碼及點選“允許”後,會跳轉回原ViewController,但無任何事發生。以下加入跳轉回原ViewController後執行的方法,此方法為GIDSignInDelegate必須實作的函數。
(目前只取出userID, email, 大頭貼進行示範,還有其餘用戶資訊可取用)
9. 以程式碼建立的部分,在viewDidLoad中初始化GIDSignInButton,並在viewDidLayoutSubView中設定位置。
10. 接著建立登出按鈕,將一個UIButton拉到storyBoard內,並將autolayout拉好,與ViewController做連接,建立@IBAction
在@IBAction內輸入以下程式碼,即可實作登出功能。