Trang này cho bạn biết cách tích hợp tính năng Đăng nhập bằng Google vào ứng dụng iOS hoặc macOS. Bạn có thể cần điều chỉnh các hướng dẫn này cho vòng đời hoặc mô hình giao diện của ứng dụng.
Trước khi bắt đầu
Tải các phần phụ thuộc xuống, định cấu hình dự án Xcode của bạn và đặt mã ứng dụng.
1. Xử lý URL chuyển hướng xác thực
iOS: UIApplicationDelegate
Trong phương thức application:openURL:options
của AppDelegate, hãy gọi phương thức handleURL:
của GIDSignIn
:
Swift
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
}
Objective-C
- (BOOL)application:(UIApplication *)app
openURL:(NSURL *)url
options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
BOOL handled;
handled = [GIDSignIn.sharedInstance handleURL:url];
if (handled) {
return YES;
}
// Handle other custom URL types.
// If not handled by this app, return NO.
return NO;
}
macOS: NSApplicationDelegate
Trong AppDelegate của ứng dụng, hãy đăng ký một trình xử lý cho các sự kiện
kAEGetURL
trongapplicationDidFinishLaunching
:Swift
func applicationDidFinishLaunching(_ notification: Notification) { // Register for GetURL events. let appleEventManager = NSAppleEventManager.shared() appleEventManager.setEventHandler( self, andSelector: "handleGetURLEvent:replyEvent:", forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL) ) }
Objective-C
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification { // Register for GetURL events. NSAppleEventManager *appleEventManager = [NSAppleEventManager sharedAppleEventManager]; [appleEventManager setEventHandler:self andSelector:@selector(handleGetURLEvent:withReplyEvent:) forEventClass:kInternetEventClass andEventID:kAEGetURL]; }
Xác định trình xử lý cho các sự kiện gọi
handleURL
củaGIDSignIn
:Swift
func handleGetURLEvent(event: NSAppleEventDescriptor?, replyEvent: NSAppleEventDescriptor?) { if let urlString = event?.paramDescriptor(forKeyword: AEKeyword(keyDirectObject))?.stringValue{ let url = NSURL(string: urlString) GIDSignIn.sharedInstance.handle(url) } }
Objective-C
- (void)handleGetURLEvent:(NSAppleEventDescriptor *)event withReplyEvent:(NSAppleEventDescriptor *)replyEvent { NSString *URLString = [[event paramDescriptorForKeyword:keyDirectObject] stringValue]; NSURL *URL = [NSURL URLWithString:URLString]; [GIDSignIn.sharedInstance handleURL:url]; }
SwiftUI
Trong cửa sổ hoặc cảnh của ứng dụng, hãy đăng ký một trình xử lý để nhận URL và gọi GIDSignIn
s handleURL
:
Swift
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
// ...
.onOpenURL { url in
GIDSignIn.sharedInstance.handle(url)
}
}
}
}
2. Cố gắng khôi phục trạng thái đăng nhập của người dùng
Khi ứng dụng của bạn khởi động, hãy gọi restorePreviousSignInWithCallback
để thử và
khôi phục trạng thái đăng nhập của người dùng đã đăng nhập bằng Google. Làm như vậy
để đảm bảo người dùng không phải đăng nhập mỗi khi mở ứng dụng (trừ khi
họ đã đăng xuất).
Ứng dụng iOS thường thực hiện việc này trong phương thức application:didFinishLaunchingWithOptions:
của UIApplicationDelegate
và applicationDidFinishLaunching:
của NSApplicationDelegate
đối với ứng dụng macOS. Sử dụng kết quả
để xác định chế độ xem nào sẽ hiển thị cho người dùng. Ví dụ:
Swift
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
}
Objective-C
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[GIDSignIn.sharedInstance restorePreviousSignInWithCompletion:^(GIDGoogleUser * _Nullable user,
NSError * _Nullable error) {
if (error) {
// Show the app's signed-out state.
} else {
// Show the app's signed-in state.
}
}];
return YES;
}
SwiftUI
Nếu bạn đang sử dụng SwiftUI, hãy thêm một lệnh gọi tới restorePreviousSignIn
trong onAppear
cho thành phần hiển thị ban đầu của bạn:
Swift
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
// ...
.onAppear {
GIDSignIn.sharedInstance.restorePreviousSignIn { user, error in
// Check if `user` exists; otherwise, do something with `error`
}
}
}
}
}
3. Thêm nút Đăng nhập bằng Google
Thêm nút "Đăng nhập bằng Google" vào Chế độ xem đăng nhập. Các thành phần hiện có cho SwiftUI và UIKit, có khả năng tự động tạo một nút có gắn thương hiệu Google và được đề xuất sử dụng.
Sử dụng SwiftUI
Hãy đảm bảo bạn đã thêm phần phụ thuộc vào nút "Đăng nhập bằng Google" của SwiftUI vào dự án.
Trong tệp mà bạn muốn thêm nút SwiftUI, hãy thêm nội dung nhập bắt buộc vào đầu tệp:
import GoogleSignInSwift
Thêm nút "Đăng nhập bằng Google" vào Chế độ xem và chỉ định hành động sẽ được gọi khi nhấn nút:
GoogleSignInButton(action: handleSignInButton)
Kích hoạt quy trình đăng nhập khi nhấn nút bằng cách thêm lệnh gọi vào phương thức
signIn(presentingViewController:completion:)
củaGIDSignIn
trong hành động của bạn:func handleSignInButton() { GIDSignIn.sharedInstance.signIn( withPresenting: rootViewController) { signInResult, error in guard let result = signInResult else { // Inspect error return } // If sign in succeeded, display the app's main content View. } ) }
Công cụ này sử dụng mô hình chế độ xem mặc định cung cấp thông tin định kiểu chuẩn cho nút. Để kiểm soát giao diện của nút, bạn cần tạo GoogleSignInButtonViewModel
tuỳ chỉnh và đặt nó làm viewModel
trong trình khởi chạy của nút bằng cách sử dụng GoogleSignInButton(viewModel: yourViewModel, action:
yourAction)
. Xem mã nguồn GoogleSignInButtonViewModel
để biết thêm thông tin.
Sử dụng UIKit
Thêm nút "Đăng nhập bằng Google" vào Chế độ xem đăng nhập. Bạn có thể sử dụng lớp
GIDSignInButton
để tự động tạo nút có thương hiệu của Google (nên dùng) hoặc tạo nút của riêng bạn với kiểu tuỳ chỉnh.Để thêm
GIDSignInButton
vào bảng phân cảnh hoặc tệp XIB, hãy thêm một Chế độ xem và đặt lớp tuỳ chỉnh thànhGIDSignInButton
. Vui lòng lưu ý khi bạn thêmGIDSignInButton
Chế độ xem vào bảng phân cảnh, nút đăng nhập sẽ không hiển thị trong trình tạo giao diện. Chạy ứng dụng để xem nút đăng nhập.Bạn có thể tuỳ chỉnh giao diện của
GIDSignInButton
bằng cách đặt các thuộc tínhcolorScheme
vàstyle
tương ứng:Thuộc tính kiểu GIDSignInButton colorScheme
kGIDSignInButtonColorSchemeLight
kGIDSignInButtonColorSchemeDark
style
kGIDSignInButtonStyleStandard
kGIDSignInButtonStyleWide
kGIDSignInButtonStyleIconOnly
Kết nối nút với một phương thức trong ViewController để gọi
signIn:
. Ví dụ: sử dụngIBAction
:Swift
@IBAction func signIn(sender: Any) { GIDSignIn.sharedInstance.signIn(withPresenting: self) { signInResult, error in guard error == nil else { return } // If sign in succeeded, display the app's main content View. } }
Objective-C
- (IBAction)signIn:(id)sender { [GIDSignIn.sharedInstance signInWithPresentingViewController:self completion:^(GIDSignInResult * _Nullable signInResult, NSError * _Nullable error) { if (error) { return; } // If sign in succeeded, display the app's main content View. }]; }
4. Thêm nút đăng xuất
Thêm nút đăng xuất vào ứng dụng, hiển thị với người dùng đã đăng nhập.
Kết nối nút với một phương thức trong ViewController để gọi
signOut:
. Ví dụ: sử dụngIBAction
:Swift
@IBAction func signOut(sender: Any) { GIDSignIn.sharedInstance.signOut() }
Objective-C
- (IBAction)signOut:(id)sender { [GIDSignIn.sharedInstance signOut]; }
Các bước tiếp theo
Giờ đây, khi người dùng có thể đăng nhập vào ứng dụng của bạn bằng Tài khoản Google, hãy tìm hiểu cách:
- Xem thông tin hồ sơ Tài khoản Google của người dùng.
- Xác thực bằng phần phụ trợ bằng mã thông báo mã nhận dạng Google của người dùng.
- Gọi các API của Google thay mặt người dùng.