1.配置Google Sign-In库
1.用之前在Google APIs Console创建的client ID初始化一个CIDConfiguration对象。
| let signInConfig = GIDConfiguration.init(clientID: "YOUR_IOS_CLIENT_ID") |
|---|
2.在你的AppDelegate’s application:openURL:options方法中,调用GIDSignIn's handleURL: method
func application(
_ app: UIApplication,
open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]
) -> Bool {
var handled: Bool
handled = GIDSignIn.sharedInstance.handle(url)
if handled {
return true
}
// Handle other custom URL types.
// If not handled by this app, return false.
return false
}
2.获取已经登录用户的登录状态
当你的app开始运作了,调用restorePreviousSignInWithCallback方法来获取已经登录的用户的登录状态。确保用户不用每次打开app重新登录。(直到他们登出)。
App通常调用这个方法并使用这个方法的结果来决定要展示的页面。如下:
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
GIDSignIn.sharedInstance.restorePreviousSignIn { user, error in
if error != nil || user == nil {
// Show the app's signed-out state.
} else {
// Show the app's signed-in state.
}
}
return true
}
3.添加谷歌登录按钮
1.在你的登录页面添加一个谷歌登录按钮。你可以使用GIDSignInButton class自动的创建一个Google官方按钮,或者你也可以创建一个你自定义的按钮。
你可以通过GIDSignInButton下面的colorScheme 和 style properties来定制你的登录按钮样式。
| GIDSignInButton style properties | |
|---|---|
| colorScheme | kGIDSignInButtonColorSchemeLight kGIDSignInButtonColorSchemeDark |
| style | kGIDSignInButtonStyleStandard kGIDSignInButtonStyleWide kGIDSignInButtonStyleIconOnly |
2.把这个按钮连接到你的ViewController控制器中,并在控制器中调用signInWithConfiguration:,传入你在本文档第一步得到的configuration 对象。如下所示代码:
@IBAction func signIn(sender: Any) {
GIDSignIn.sharedInstance.signIn(with: signInConfig, presenting: self) { user, error in
guard error == nil else { return }
// If sign in succeeded, display the app's main content View.
}
}
4. 登出按钮
1.加入一个登出按钮到你的app
2.连接这个按钮到ViewController,并且调用signOut:方法: 。如下所示代码:
@IBAction func signOut(sender: Any) {
GIDSignIn.sharedInstance.signOut()
}
5.获取用户信息
如果用户已经验证了并授权了你请求的数据,你就可以通过GIDGoogleUser对象访问用户的profile信息了
一旦用户验证了请求,
GIDSignIn.sharedInstance.signIn(with: signInConfig, presenting: self) { user, error in
guard error == nil else { return }
guard let user = user else { return }
let emailAddress = user.profile?.email
let fullName = user.profile?.name
let givenName = user.profile?.givenName
let familyName = user.profile?.familyName
let profilePicUrl = user.profile?.imageURL(withDimension: 320)
}
若有收获,就点个赞吧