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. Có thể bạn sẽ 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 khách của bạn.
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 của GIDSignIn
Phương thức handleURL::
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]; }Định nghĩa trình xử lý cho những sự kiện 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
handleURL của GIDSignIn:
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 để dùng 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. Đang thực hiện
đảm bảo người dùng không phải đăng nhập mỗi khi họ mở ứng dụng của bạn (trừ khi
họ đã đăng xuất).
Các ứng dụng iOS thường thực hiện việc này trong phần UIApplicationDelegate
Phương thức application:didFinishLaunchingWithOptions: và
applicationDidFinishLaunching: của NSApplicationDelegate cho ứ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 vào restorePreviousSignIn trong onAppear cho
chế độ xem 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 có sẵn cho SwiftUI và UIKit tự động tạo một có thương hiệu Google và nên sử dụng.
Sử dụng SwiftUI
Đảm bảo rằng bạn đã thêm phần phụ thuộc cho tính năng "Đăng nhập bằng Google" của SwiftUI nút cho dự án của bạ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 GoogleSignInSwiftThêm nút "Đăng nhập bằng Google" vào Chế độ xem của bạn và chỉ định hành động sẽ được gọi khi người dùng nhấn nút này:
GoogleSignInButton(action: handleSignInButton)Kích hoạt quá trình đăng nhập khi người dùng nhấn nút này bằng cách thêm một lệnh gọi đến Điều khoản dịch vụ và Chính sách quyền riêng tư của
GIDSignInPhương thứcsignIn(presentingViewController:completion:)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. } ) }
Hàm 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 giao diện người dùng
GoogleSignInButtonViewModel rồi đặt làm viewModel trong nút
bằ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
GIDSignInButtonlớp để tự động tạo một nút bằng Google xây dựng thương hiệu (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 lớp đó thànhGIDSignInButton. Xin lưu ý rằng khi bạn thêm mộtGIDSignInButtonXem bảng phân cảnh của bạn, nút đăng nhập 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 Thuộc tínhcolorSchemevàstyle:Thuộc tính kiểu GIDSignInButton colorSchemekGIDSignInButtonColorSchemeLight
kGIDSignInButtonColorSchemeDarkstylekGIDSignInButtonStyleStandard
kGIDSignInButtonStyleWide
kGIDSignInButtonStyleIconOnlyKết nối nút này với một phương thức trong ViewController mà phương thức này 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 một nút đăng xuất vào ứng dụng của bạn mà người dùng đã đăng nhập có thể nhìn thấy.
Kết nối nút này với một phương thức trong ViewController mà phương thức này 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 thức thành:
- Lấy thông tin của người dùng Thông tin trong hồ sơ Tài khoản Google.
- Xác thực bằng phần phụ trợ bằng mã Google của người dùng mã thông báo.
- Gọi API của Google thay mặt người dùng.