Tích hợp tính năng Đăng nhập bằng Google vào ứng dụng iOS hoặc macOS của bạn

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 trên iOS hoặc macOS. Bạn có thể cần điều chỉnh các hướng dẫn này cho phù hợp với 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 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.

Hãy dùng thử ứng dụng mẫu dành cho iOS và macOS của chúng tôi để xem cách hoạt động của tính năng Đăng nhập.

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

  1. Trong AppDelegate của ứng dụng, hãy đăng ký một trình xử lý cho các sự kiện kAEGetURL trong applicationDidFinishLaunching:

    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];
    }
    
  2. Xác định trình xử lý cho các sự kiện gọi handleURL của GIDSignIn:

    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 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 để 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. Việc này đảm bảo người dùng không phải đăng nhập mỗi khi mở ứng dụng (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 application:didFinishLaunchingWithOptions: của UIApplicationDelegateapplicationDidFinishLaunching: của NSApplicationDelegate đối với ứng dụng macOS. Sử dụng kết quả để xác định thành phần hiển thị sẽ hiển thị với 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 để xem 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 Chế độ xem khi đăng nhập. SwiftUI và UIKit tự động tạo một nút có thương hiệu của Google và nên sử dụng các thành phần này.

Sử dụng SwiftUI

  1. Đảm bảo bạn đã thêm phần phụ thuộc cho nút "Sign in with Google" (Đăng nhập bằng Google) của SwiftUI vào dự án.

  2. Trong tệp mà bạn muốn thêm nút SwiftUI, hãy thêm dữ liệu nhập cần thiết vào đầu tệp:

    import GoogleSignInSwift
    
  3. Thê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 nhấn nút này:

    GoogleSignInButton(action: handleSignInButton)
    
  4. 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 vào phương thức signIn(presentingViewController:completion:) của GIDSignIn trong 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 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 một GoogleSignInButtonViewModel tuỳ chỉnh và đặt làm viewModel trong trình khởi động của nút bằng GoogleSignInButton(viewModel: yourViewModel, action: yourAction). Hãy xem mã nguồn GoogleSignInButtonViewModel để biết thêm thông tin.

Sử dụng UIKit

  1. Thêm nút "Đăng nhập bằng Google" vào Chế độ xem khi đă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 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 Thành phần hiển thị và đặt lớp tuỳ chỉnh của thành phần hiển thị đó thành GIDSignInButton. Lưu ý rằng khi bạn thêm một Chế độ xem GIDSignInButton 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ính colorSchemestyle:

    Thuộc tính kiểu GIDSignInButton
    colorScheme kGIDSignInButtonColorSchemeLight
    kGIDSignInButtonColorSchemeDark
    style kGIDSignInButtonStyleStandard
    kGIDSignInButtonStyleWide
    kGIDSignInButtonStyleIconOnly
  2. Kết nối nút với một phương thức trong ViewController gọi signIn:. Ví dụ: sử dụng IBAction:

    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

  1. Thêm nút đăng xuất vào ứng dụng của bạn, hiển thị với người dùng đã đăng nhập.

  2. Kết nối nút với một phương thức trong ViewController gọi signOut:. Ví dụ: sử dụng IBAction:

    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 của họ, hãy tìm hiểu cách: