返回
iOS 接入 Google、Facebook 登录(二):添加 SDK 和登录功能
IOS
2024-01-01 00:47:00
导入 SDK
在您的项目中添加 Google 和 Facebook 的 SDK。
-
Google :打开 Firebase 控制台,点击“添加应用”。按照屏幕上的说明创建新的 Firebase 应用。添加完成后,点击“下载 GoogleService-Info.plist”按钮,并将文件添加到您的 Xcode 项目中。
-
Facebook :打开 Facebook 开发者平台,点击“添加新应用”。按照屏幕上的说明创建新的 Facebook 应用。添加完成后,点击“设置”选项卡,然后点击“基本设置”部分。找到“应用 ID”和“应用密码”,并将其添加到您的 Xcode 项目中。
添加登录按钮
在您的应用程序中添加 Google 和 Facebook 登录按钮。
- Google :将以下代码添加到您的应用程序的界面文件中:
<button type="button" class="btn btn-google" onclick="signInWithGoogle()">Sign in with Google</button>
- Facebook :将以下代码添加到您的应用程序的界面文件中:
<button type="button" class="btn btn-facebook" onclick="signInWithFacebook()">Sign in with Facebook</button>
实现登录功能
在您的应用程序中实现 Google 和 Facebook 登录功能。
- Google :将以下代码添加到您的应用程序的 Swift 文件中:
func signInWithGoogle() {
let googleButton = GIDSignInButton()
googleButton.frame = CGRect(x: 0, y: 0, width: 200, height: 48)
googleButton.addTarget(self, action: #selector(handleGoogleSignIn), for: .touchUpInside)
self.view.addSubview(googleButton)
}
@objc func handleGoogleSignIn(_ sender: UIButton) {
GIDSignIn.sharedInstance().signIn()
}
- Facebook :将以下代码添加到您的应用程序的 Swift 文件中:
func signInWithFacebook() {
let loginButton = FBLoginButton()
loginButton.frame = CGRect(x: 0, y: 0, width: 200, height: 48)
loginButton.delegate = self
self.view.addSubview(loginButton)
}
func loginButton(_ loginButton: FBLoginButton, didCompleteWith result: LoginManagerLoginResult?, error: Error?) {
if let error = error {
print(error.localizedDescription)
return
}
let credential = FacebookAuthProvider.credential(withAccessToken: result!.token!.tokenString)
Auth.auth().signIn(with: credential)
}
func loginButtonDidLogOut(_ loginButton: FBLoginButton) {
// Handle the logout
}
处理登录结果
在您的应用程序中处理 Google 和 Facebook 登录的结果。
- Google :将以下代码添加到您的应用程序的 Swift 文件中:
func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
if let error = error {
print(error.localizedDescription)
return
}
let credential = GoogleAuthProvider.credential(withIDToken: user.authentication.idToken, accessToken: user.authentication.accessToken)
Auth.auth().signIn(with: credential)
}
- Facebook :将以下代码添加到您的应用程序的 Swift 文件中:
func authStateDidChange(_ auth: Auth) {
if auth.currentUser != nil {
// User is signed in
} else {
// User is not signed in
}
}
结论
现在您已经成功地在您的 iOS 项目中添加了 Google 和 Facebook 的登录功能。您可以使用这些功能来让用户轻松地登录您的应用程序,并访问他们各自的账户信息。