0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

GoogleのAPIを使用してGoogleログイン機能

Posted at

AppDelegate.swift
GoogleAPIを使うためのトークンの設定

import Foundation

import UIKit
import GoogleSignIn

class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Initialize sign-in
        // Google Sign-Inの初期化
        GIDSignIn.sharedInstance.configuration = GIDConfiguration(clientID: "トークン文字列")

        return true
    }

    func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
        return GIDSignIn.sharedInstance.handle(url)
    }
}

ContentView.swift

import SwiftUI
import Vision
import VisionKit

import SwiftUI
import GoogleSignIn

struct ContentView: View {
    @StateObject private var signInHandler = SignInHandler()

    var body: some View {
        VStack {
            if let user = signInHandler.user {//-------ログインに成功した場合
                Text("こんにちは!!, \(user.profile?.name ?? "User")")
                Button(action: {
                    signInHandler.signOut()
                }) {
                    Text("ログアウトする")
                }
            } else {//---------------ログアウト状態の場合
                GoogleSignInButton {
                    signInHandler.signIn()
                }
                .frame(width: 200, height: 50)
                .padding()
            }
        }
    }
}


struct GoogleSignInButton: View {
    let action: () -> Void

    var body: some View {
        Button(action: action) {
            HStack {
                Image(systemName: "globe") 
                Text("サインインボタン")
            }
            .frame(width: 200, height: 50)
            .background(Color.blue)
            .foregroundColor(.white)
            .cornerRadius(10)
        }
    }
}

class SignInHandler: ObservableObject {
    @Published var user: GIDGoogleUser?

    func signIn() {
        guard let rootViewController = getRootViewController() else {
            return
        }
        GIDSignIn.sharedInstance.signIn(withPresenting: rootViewController) { signInResult, error in
            if let error = error {
                print("Error signing in: \(error.localizedDescription)")
                return
            }
            guard let user = signInResult?.user else { return }
            DispatchQueue.main.async {
                self.user = user
                print("User signed in: \(user.profile?.name ?? "No Name")")
            }
        }
    }

    func signOut() {
        GIDSignIn.sharedInstance.signOut()
        DispatchQueue.main.async {
            self.user = nil
        }
    }

    private func getRootViewController() -> UIViewController? {
        guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
              let window = windowScene.windows.first else {
            return nil
        }
        return window.rootViewController
    }
}


#Preview {
    ContentView()
}

見た目部分(メイン)

struct ContentView: View {
    @StateObject private var signInHandler = SignInHandler()

    var body: some View {
        VStack {
            if let user = signInHandler.user {//-------ログインに成功した場合
                Text("こんにちは!!, \(user.profile?.name ?? "User")")
                Button(action: {
                    signInHandler.signOut()
                }) {
                    Text("ログアウトする")
                }
            } else {//---------------ログアウト状態の場合
                GoogleSignInButton {
                    signInHandler.signIn()
                }
                .frame(width: 200, height: 50)
                .padding()
            }
        }
    }
}

ログインボタン部分

struct GoogleSignInButton: View {
    let action: () -> Void

    var body: some View {
        Button(action: action) {
            HStack {
                Image(systemName: "globe") // ここにGoogleのロゴを追加するか、カスタムビューを使用できます
                Text("サインインボタン")
            }
            .frame(width: 200, height: 50)
            .background(Color.blue)
            .foregroundColor(.white)
            .cornerRadius(10)
        }
    }
}

ログインの関数用クラス

class SignInHandler: ObservableObject {
    @Published var user: GIDGoogleUser?

    func signIn() {
        guard let rootViewController = getRootViewController() else {
            return
        }
        GIDSignIn.sharedInstance.signIn(withPresenting: rootViewController) { signInResult, error in
            if let error = error {
                print("Error signing in: \(error.localizedDescription)")
                return
            }
            guard let user = signInResult?.user else { return }
            DispatchQueue.main.async {
                self.user = user
                print("User signed in: \(user.profile?.name ?? "No Name")")
            }
        }
    }

    func signOut() {
        GIDSignIn.sharedInstance.signOut()
        DispatchQueue.main.async {
            self.user = nil
        }
    }

    private func getRootViewController() -> UIViewController? {
        guard let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
              let window = windowScene.windows.first else {
            return nil
        }
        return window.rootViewController
    }
}

ログイン用の関数

    func signIn() {
        guard let rootViewController = getRootViewController() else {
            return
        }
        GIDSignIn.sharedInstance.signIn(withPresenting: rootViewController) { signInResult, error in
            if let error = error {
                print("Error signing in: \(error.localizedDescription)")
                return
            }
            guard let user = signInResult?.user else { return }
            DispatchQueue.main.async {
                self.user = user
                print("User signed in: \(user.profile?.name ?? "No Name")")
            }
        }
    }
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?