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 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.

Hãy dùng thử ứng dụng mẫu của chúng tôi trên iOS và macOS để 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

Sau khi người dùng xác thực bằng Google, quy trình xác thực sẽ chuyển hướng trở lại ứng dụng của bạn bằng một URL chứa phản hồi xác thực, bao gồm cả mã thông báo nhận dạng của người dùng. Việc truyền URL này đến GIDSignIn cho phép SDK phân tích cú pháp phản hồi và trả về thông tin đăng nhập của người dùng cho ứng dụng của bạn.

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 những sự kiện này, 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 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:applicationDidFinishLaunching: của NSApplicationDelegate đối với 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 chế độ xem đă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 tuân thủ nguyên tắc sử dụng thương hiệu của Google.

Sử dụng SwiftUI

  1. Đả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.

  2. 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
    
  3. Thêm một tiện ích UIApplication để truy xuất trình điều khiển khung hiển thị gốc đang hoạt động để trình bày:

    extension UIApplication {
      // Minimal implementation to retrieve the active root view
      // controller for presentation. Apps presenting sign-in from deeper
      // within an existing view hierarchy should ensure they select the
      // appropriate view controller.
      var rootViewController: UIViewController? {
        let windowScene = connectedScenes
          .compactMap { scene in scene as? UIWindowScene }
          .first { scene in scene.activationState == .foregroundActive }
        return windowScene?.windows.first(where: { window in window.isKeyWindow })?.rootViewController
      }
    }
    
  4. Thê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)
    
  5. 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(withPresenting:completion:) của GIDSignIn trong thao tác của bạn:

    func handleSignInButton() {
      guard let rootViewController = UIApplication.shared.rootViewController else {
        // Handle error
        return
      }
    
      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 khung 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 GoogleSignInButtonViewModel mã nguồn để biết thêm thông tin.

Sử dụng UIKit

  1. 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 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 của chế độ xem đó thành GIDSignInButton. Xin 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

Thêm một nút đăng xuất vào ứng dụng của bạn (người dùng đã đăng nhập có thể thấy nút này). Nút này sẽ gọi phương thức signOut của GIDSignIn.

Việc gọi signOut sẽ xoá trạng thái đăng nhập được lưu trữ trong GIDSignIn và xoá thông tin đăng nhập của người dùng cho ứng dụng của bạn khỏi Keychain. Ứng dụng của bạn chịu trách nhiệm cập nhật trạng thái và giao diện người dùng của chính ứng dụng. Thao tác đăng xuất chỉ áp dụng cho ứng dụng của bạn. Thao tác này không đăng xuất người dùng khỏi các ứng dụng hoặc dịch vụ khác và không thu hồi các quyền mà người dùng đã cấp cho ứng dụng của bạn.

Sử dụng SwiftUI

Trong SwiftUI, hãy thêm một Button gọi GIDSignIn.sharedInstance.signOut():

Button("Sign Out") {
  GIDSignIn.sharedInstance.signOut()
  // Calling signOut() may not automatically trigger UI updates.
  // Update your app's state as needed.
}

Sử dụng UIKit

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. Hãy tìm hiểu cách: