Trang này hướng dẫn cách tích hợp tính năng Đăng nhập bằng Google vào một ứ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 người dùng 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 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
kAEGetURLtrongapplicationDidFinishLaunching: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 những sự kiện này, gọi
handleURLcủ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 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 khởi động, hãy gọi restorePreviousSignInWithCallback để thử khôi phục trạng thái đăng nhập của những người dùng đã đăng nhập bằng Google. Việc này giúp đảm bảo người dùng không phải đăng nhập mỗi khi mở ứng dụng của bạn (trừ phi họ đã đăng xuất).
Các ứng dụng iOS thường thực hiện việc này trong phương thức UIApplicationDelegate của application:didFinishLaunchingWithOptions: và NSApplicationDelegate của applicationDidFinishLaunching: cho các ứng dụng macOS. Sử dụng kết quả này để xác định khung hiển thị nào sẽ trình bày 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 đến restorePreviousSignIn trong onAppear cho khung hiển thị ban đầu:
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 khung hiển thị đăng nhập. Các thành phần có sẵn cho SwiftUI và UIKit sẽ tự động tạo một nút có thương hiệu của Google và bạn nên sử dụng.
Sử dụng SwiftUI
Đảm bảo rằng bạn đã thêm phần phụ thuộc cho nút "Đăng nhập bằng Google" của SwiftUI vào dự án của mình.
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 GoogleSignInSwiftThêm nút "Đăng nhập bằng Google" vào Khung hiển thị và chỉ định thao tác sẽ được gọi khi người dùng nhấn nút:
GoogleSignInButton(action: handleSignInButton)Kích hoạt quy trình đăng nhập khi người dùng nhấn vào nút bằng cách thêm một lệnh gọi đến phương thức
signIn(presentingViewController:completion:)củaGIDSignIntrong thao tác 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. } ) }
Thao tác này sử dụng mô hình hiển thị mặc định cung cấp thông tin tạo kiểu tiêu chuẩn cho nút. Để kiểm soát giao diện của nút, bạn cần tạo một GoogleSignInButtonViewModel tuỳ chỉnh và đặt nút đó làm viewModel trong trình khởi tạo của nút bằng cách sử dụng GoogleSignInButton(viewModel: yourViewModel, action:
yourAction). Hãy 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 khung hiển thị đăng nhập. Bạn có thể sử dụng lớp
GIDSignInButtonđể tự động tạo một nút có thương hiệu 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
GIDSignInButtonvà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 của chế độ xem đó thànhGIDSignInButton. Xin lưu ý rằng khi bạn thêm một Chế độ xemGIDSignInButtonvà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
GIDSignInButtonbằng cách đặt các thuộc tínhcolorSchemevàstyle:Thuộc tính kiểu GIDSignInButton colorSchemekGIDSignInButtonColorSchemeLight
kGIDSignInButtonColorSchemeDarkstylekGIDSignInButtonStyleStandard
kGIDSignInButtonStyleWide
kGIDSignInButtonStyleIconOnlyKế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 của bạn, người dùng đã đăng nhập có thể nhìn thấy nút này.
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, 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:
- Lấy 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 trên Google của người dùng.
- Gọi API của Google thay cho người dùng.