ادغام Google Sign-In در برنامه iOS یا macOS شما

این صفحه به شما نشان می دهد که چگونه Google Sign-In را در یک برنامه iOS یا macOS ادغام کنید. ممکن است لازم باشد این دستورالعمل‌ها را برای چرخه عمر برنامه یا مدل UI تطبیق دهید.

قبل از اینکه شروع کنی

وابستگی ها را دانلود کنید، پروژه Xcode خود را پیکربندی کنید و شناسه مشتری خود را تنظیم کنید .

برنامه نمونه iOS و macOS ما را امتحان کنید تا ببینید ورود به سیستم چگونه کار می‌کند .

1. URL تغییر مسیر احراز هویت را مدیریت کنید

iOS: UIApplicationDelegate

در application:openURL:options ، روش handleURL: GIDSignIn را فراخوانی کنید:

سریع

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
}

هدف-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. در AppDelegate برنامه خود یک کنترل کننده برای رویدادهای kAEGetURL در applicationDidFinishLaunching ثبت کنید:

    سریع

    func applicationDidFinishLaunching(_ notification: Notification) {
      // Register for GetURL events.
      let appleEventManager = NSAppleEventManager.shared()
      appleEventManager.setEventHandler(
        self,
        andSelector: "handleGetURLEvent:replyEvent:",
        forEventClass: AEEventClass(kInternetEventClass),
        andEventID: AEEventID(kAEGetURL)
      )
    }
    

    هدف-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. کنترل کننده ای را برای این رویدادها تعریف کنید که GIDSignIn 's handleURL را فراخوانی می کند:

    سریع

    func handleGetURLEvent(event: NSAppleEventDescriptor?, replyEvent: NSAppleEventDescriptor?) {
        if let urlString =
          event?.paramDescriptor(forKeyword: AEKeyword(keyDirectObject))?.stringValue{
            let url = NSURL(string: urlString)
            GIDSignIn.sharedInstance.handle(url)
        }
    }
    

    هدف-C

    - (void)handleGetURLEvent:(NSAppleEventDescriptor *)event
               withReplyEvent:(NSAppleEventDescriptor *)replyEvent {
          NSString *URLString = [[event paramDescriptorForKeyword:keyDirectObject] stringValue];
          NSURL *URL = [NSURL URLWithString:URLString];
          [GIDSignIn.sharedInstance handleURL:url];
    }
    

SwiftUI

در پنجره یا صحنه برنامه خود، یک کنترل کننده برای دریافت URL ثبت کنید و با handleURL GIDSignIn تماس بگیرید:

سریع

@main
struct MyApp: App {

  var body: some Scene {
    WindowGroup {
      ContentView()
        // ...
        .onOpenURL { url in
          GIDSignIn.sharedInstance.handle(url)
        }
    }
  }
}

2. سعی کنید وضعیت ورود به سیستم کاربر را بازیابی کنید

وقتی برنامه شما راه اندازی شد، با restorePreviousSignInWithCallback تماس بگیرید تا وضعیت ورود به سیستم کاربرانی را که قبلاً با استفاده از Google وارد سیستم شده اند بازیابی کنید. انجام این کار باعث می شود کاربران مجبور نباشند هر بار که برنامه شما را باز می کنند وارد سیستم شوند (مگر اینکه از سیستم خارج شده باشند).

برنامه‌های iOS اغلب این کار را در برنامه UIApplicationDelegate application:didFinishLaunchingWithOptions: metod و NSApplicationDelegate applicationDidFinishLaunching: برای برنامه‌های macOS انجام می‌دهند. از نتیجه برای تعیین اینکه کدام نما به کاربر ارائه شود استفاده کنید. مثلا:

سریع

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
}

هدف-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

اگر از SwiftUI استفاده می‌کنید، برای نمای اولیه خود، تماسی برای restorePreviousSignIn onAppear اضافه کنید:

سریع

@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. یک دکمه ورود به سیستم گوگل اضافه کنید

یک دکمه "ورود به سیستم با Google" را به نمای ورود به سیستم خود اضافه کنید. مؤلفه‌هایی برای SwiftUI و UIKit در دسترس هستند که به‌طور خودکار یک دکمه با مارک Google ایجاد می‌کنند و برای استفاده توصیه می‌شوند.

با استفاده از SwiftUI

  1. مطمئن شوید که وابستگی دکمه SwiftUI "Sign in with Google" را به پروژه خود اضافه کرده اید.

  2. در فایلی که می‌خواهید دکمه SwiftUI را اضافه کنید، وارد کردن مورد نیاز را به بالای فایل اضافه کنید:

    import GoogleSignInSwift
    
  3. یک دکمه "ورود به سیستم با Google" را به نمای خود اضافه کنید و عملکردی را که با فشار دادن دکمه فراخوانی می شود را مشخص کنید:

    GoogleSignInButton(action: handleSignInButton)
    
  4. با افزودن یک تماس به روش signIn(presentingViewController:completion:) GIDSignIn در اقدام خود، فرآیند ورود به سیستم را هنگامی که دکمه فشار داده می شود، راه اندازی کنید:

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

این از مدل نمای پیش‌فرض استفاده می‌کند که اطلاعات سبک استانداردی را برای دکمه ارائه می‌کند. برای کنترل ظاهر دکمه، باید یک GoogleSignInButtonViewModel سفارشی ایجاد کنید و آن را با استفاده از GoogleSignInButton(viewModel: yourViewModel, action: yourAction) به عنوان viewModel در مقداردهی اولیه دکمه تنظیم کنید. برای اطلاعات بیشتر به کد منبع GoogleSignInButtonViewModel مراجعه کنید.

با استفاده از UIKit

  1. یک دکمه "ورود به سیستم با Google" را به نمای ورود به سیستم خود اضافه کنید. می‌توانید از کلاس GIDSignInButton برای ایجاد خودکار دکمه‌ای با نام تجاری Google (توصیه می‌شود) استفاده کنید یا دکمه خود را با استایل سفارشی ایجاد کنید.

    برای افزودن یک GIDSignInButton به استوری برد یا فایل XIB، یک View اضافه کنید و کلاس سفارشی آن را روی GIDSignInButton تنظیم کنید. توجه داشته باشید که وقتی یک نمای GIDSignInButton را به استوری‌برد خود اضافه می‌کنید، دکمه ورود به سیستم در سازنده رابط نمایش داده نمی‌شود. برنامه را اجرا کنید تا دکمه ورود به سیستم را ببینید.

    می‌توانید ظاهر یک GIDSignInButton را با تنظیم ویژگی‌های colorScheme و style آن سفارشی کنید:

    ویژگی های سبک GIDSignInButton
    colorScheme kGIDSignInButtonColorSchemeLight
    kGIDSignInButtonColorSchemeDark
    style kGIDSignInButtonStyleStandard
    kGIDSignInButtonStyleWide
    kGIDSignInButtonStyleIconOnly
  2. دکمه را به روشی در ViewController خود وصل کنید که signIn: . به عنوان مثال، از یک IBAction استفاده کنید:

    سریع

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

    هدف-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. یک دکمه خروج اضافه کنید

  1. یک دکمه خروج از سیستم را به برنامه خود اضافه کنید که برای کاربرانی که وارد سیستم شده اند قابل مشاهده باشد.

  2. دکمه را به روشی در ViewController خود وصل کنید که signOut: . به عنوان مثال، از یک IBAction استفاده کنید:

    سریع

    @IBAction func signOut(sender: Any) {
      GIDSignIn.sharedInstance.signOut()
    }
    

    هدف-C

    - (IBAction)signOut:(id)sender {
      [GIDSignIn.sharedInstance signOut];
    }
    

مراحل بعدی

اکنون که کاربران می توانند با استفاده از حساب های Google خود وارد برنامه شما شوند، یاد بگیرید که چگونه: