fc2ブログ

記事一覧

Google SignInでログイン認証する方法 -iOS編- | Xamarin.Forms


今回はXamarin.iOSでGoogleのログイン認証を行う方法についてご紹介いたします。
最終的にはGoogleカレンダーに同期をとる予定ですが、OAuth2がPortableLibraryに対応しておらず、こちらの認証で行こうと思っています。
尚、Androidは次回の記事にてご紹介しており、iOSとAndroidで共通の処理になるように記述したソースがご覧になれます。


xamarin_google_signin_00.png



前提条件
・Windows10 Pro 64Bit
・Visual Studio 2015 Community Update3
・Xamarin 4.4.0.34 (NuGet Xamarin.Forms 2.3.4.247)
・macOS Sierra 10.12.4 / Xcode8.3.1 / Xamarin.iOS 10.8.0.1



1.NuGetパッケージをインストールする

iOSプロジェクトにXamarin.Google.iOS.SignInをインストールします。 「Google sign-in」で検索するとすぐに見つかります。

xamarin_google_signin_01.png



2.Google Developersの登録

(1)ブラウザでGoogle DevelopersのURLを開きます。
  https://developers.google.com/mobile/add
(2)Pick a Platform ボタンを押下します。
(3)iOS Appボタンを押下します。
(4)App nameに アプリの名前を入力します。
(5)iOS Bundle ID には com.CompanyName.AppName のようにフル名称を入力します。
(6)share your ...のチェックを外し、YourCountry に日本を選択して Choose and Configure serviceボタンを押下します。
(7)Google Sign-In を選択して Generate configuration filesボタンを押下します。

xamarin_google_signin_02.png

これでGoogleService-Info.plistファイルが取得できますので、iOSプロジェクトの直下に配置します。
また、GoogleService-Info.plistファイルはVSで以下のように設定します。
ビルドアクション:BundleResource

※以下のURLからもプロジェクトを指定することでplistファイルの生成が可能です。
https://console.developers.google.com/apis/credentials



3.Info.plistに追記

dictタグ内に以下の記述を追記します。CFBundleURLSchemesには先ほどダウンロードしたGoogleService-Info.plistファイルの中に記述があるREVERSED_CLIENT_IDの値をコピペします。

<key>CFBundleURLTypes</key>
  <array>
    <dict>
      <key>CFBundleURLTypes</key>
      <string>Editor</string>
      <key>CFBundleURLSchemes</key>
      <array>
        <string>com.googleusercontent.apps.999999999999-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx</string>
      </array>
    </dict>
    <dict>
      <key>CFBundleURLTypes</key>
      <string>Editor</string>
      <key>CFBundleURLSchemes</key>
      <array>
        <string>com.CompanyName.AppName</string>
      </array>
    </dict>
  </array>



4.PCLの記述

ログイン処理・ログアウト処理・切断処理はAndroidと共通のPCLのXAML画面から呼び出したいので、PCLプロジェクト内にDependencyServiceで呼び出すためのインターフェースを配置します。
IGoogleSignInService.cs
namespace AppName.Services
{
    //DependencyServiceから利用する
    public interface IGoogleSignInService
    {
        void SignIn();
        void SignOut();
        void Disconnect();
    }
}



5.iOSプロジェクトの記述

iOSプロジェクト内に以下のクラスを配置します。
ログイン処理・ログアウト処理・切断処理を実装します。

GoogleSignInService.cs
using Google.SignIn;
[assembly: Dependency(typeof(GoogleSignInService))]
namespace AppName.iOS.Services
{
    public class GoogleSignInService : IGoogleSignInService
    {
        public static ISignInUIDelegate SignInUIDelegate = new GoogleSignInUIDelegate();
       
        public void SignIn()
        {
            Google.SignIn.SignIn.SharedInstance.UIDelegate = SignInUIDelegate;

var googleServiceDictionary = NSDictionary.FromFile("GoogleService-Info.plist");
Google.SignIn.SignIn.SharedInstance.ClientID = googleServiceDictionary["CLIENT_ID"].ToString();

            Google.SignIn.SignIn.SharedInstance.SignedIn += (sender, e) => {
                // ここにログイン後の処理を記述します。
                if (e.User != null && e.Error == null)
                {
                    //ここにログイン成功時の処理を記述してください
                    System.Diagnostics.Debug.WriteLine("Signed in user: {0}", e.User.Profile.Name);
                }
            };

            Google.SignIn.SignIn.SharedInstance.Disconnected += (sender, e) => {
                //ここに切断時の処理を記述してください
                System.Diagnostics.Debug.WriteLine("Disconnected user");
            };

            //自動サイレントログイン
            //Google.SignIn.SignIn.SharedInstance.SignInUserSilently();
            //手動ログイン
            Google.SignIn.SignIn.SharedInstance.SignInUser();
        }

        public void SignOut()
        {
            Google.SignIn.SignIn.SharedInstance.SignOutUser();
        }

        public void Disconnect()
        {
            Google.SignIn.SignIn.SharedInstance.DisconnectUser();
        }

    }

    public class GoogleSignInUIDelegate : SignInUIDelegate
    {
        public override void WillDispatch(SignIn signIn, NSError error)
        {
        }
        public override void PresentViewController(SignIn signIn, UIViewController viewController)
        {
            UIApplication.SharedApplication.KeyWindow.RootViewController.PresentViewController(viewController, true, null);

        }

        public override void DismissViewController(SignIn signIn, UIViewController viewController)
        {
            UIApplication.SharedApplication.KeyWindow.RootViewController.DismissViewController(true, null);
        }
    }
}



6.AppDelegateの記述

AppDelegate.csに以下の記述を追加します。

using Google.SignIn;
namespace AppName.iOS
{
    [Register("AppDelegate")]
    public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
    {
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            global::Xamarin.Forms.Forms.Init();
            LoadApplication(new App());
            return base.FinishedLaunching(app, options);
        }

// For iOS 9 or newer
        public override bool OpenUrl(UIApplication app, NSUrl url, NSDictionary options)
        {
            var openUrlOptions = new UIApplicationOpenUrlOptions(options);
            return SignIn.SharedInstance.HandleUrl(url, openUrlOptions.SourceApplication, openUrlOptions.Annotation);
        }
        // For iOS 8 and older
        public override bool OpenUrl(UIApplication application, NSUrl url, string sourceApplication, NSObject annotation)
        {
            return SignIn.SharedInstance.HandleUrl(url, sourceApplication, annotation);
        }
    }
}



7.使用方法

PCLプロジェクトの中の任意のページに記述します。
TestPage.xaml.cs
void OnGoogleSignInClick(object sender, EventArgs e)
{
    DependencyService.Get<IGoogleSignInService>().SignIn();
    DependencyService.Get<IGoogleSignInService>().SignOut();
    DependencyService.Get<IGoogleSignInService>().Disconnect();
}




当ブログの内容をまとめた Xamarin逆引きメニュー は以下のURLからご覧になれます。
https://itblog.dynaspo.com/blog-entry-81.html


関連記事

コメント

コメントの投稿

※名前とタイトルが入力されていないコメントでは他のコメントとの区別ができません。

 入力されていないコメントには返信しませんのであらかじめご了承くださいませ。

※ニックネームでも良いので必ずご入力ください。

    

※必ずご入力ください。

    
    

※必ずご入力ください。

※技術的な質問には環境やエラーについて正確かつ詳細にお教えください。

・正確なエラーの内容

・Windowsのバージョン番号

・Visual Studioのバージョン

・機器の型番

・アプリやソフトのバージョン

    

カテゴリ別記事一覧

広告

プロフィール

石河 純


著者名 :石河 純
自己紹介:素人上がりのIT技術者。趣味は卓球・車・ボウリング

IT関連の知識はざっくりとこんな感じです。
【OS関連】
WindowsServer: 2012/2008R2/2003/2000/NT4
Windows: 10/8/7/XP/2000/me/NT4/98
Linux: CentOS RedHatLinux9
Mac: macOS Catalina 10.15 / Mojave 10.14 / High Sierra 10.13 / Sierra 10.12 / OSX Lion 10.7.5 / OSX Snow Leopard 10.6.8
【言語】
VB.net ASP.NET C#.net Java VBA
Xamarin.Forms
【データベース】
Oracle 10g/9i
SQLServer 2016/2008R2/2005/2000
SQLAnywhere 16/11/8
【BI/レポートツール】
Cognos ReportNet (IBM)
Microsoft PowerBI
ActiveReport (GrapeCity)
CrystalReport
【OCX関連】
GrapeCity InputMan SPREAD MultiRow GridView
【ネットワーク関連】
CCNP シスコ技術者認定
Cisco Catalyst シリーズ
Yamaha RTXシリーズ
FireWall関連
【WEB関連】
SEO SEM CSS jQuery IIS6/7 apache2

休みの日は卓球をやっています。
現在、卓球用品通販ショップは休業中です。