본문 바로가기

IOS

[IOS]유니티 애플로 로그인 구현하기 1

[Overview]

[개요]

2020년 4월 이후로 다른 소셜로그인을 제공한다면 (페이스북 , 구글 등) 애플 로그인을 같이 제공하지 않으면

업데이트 거절 사유가 되었다. ios 서비스를 위해 애플 로그인을 구현하려 한다.

[설치]

=>설치는 두가지 방식을 지원한다 .

 

[Unity Package Manager 사용]

유니티 2018.3. 버전부터 가능하다.유니티 프로젝트를 Show in Explorer로 열면  Packages/manifest.json가 있다.

manifest.json에 하단 내용을 추가한다.  Manifest에 관하여

"dependencies": {
    "com.lupidan.apple-signin-unity": "https://github.com/lupidan/apple-signin-unity.git#v1.4.2",
}

다만 , 해당 방식은 git이 설치되어 있어야 하고 , 환경변수의 path에 git.exe의 경로가 명시되어야 한다.

소스트리의 경우 해당 경로 참고 (User >> "내 컴 이름" >> Appdata >> Atlassian >> Sourcetree >> git _local >>cmd)

 

[Unity Package File 사용]

여기에서 패키지 파일을 받을 수 있다 .

다운을 받으면 AppleAuth에는 메인 플러그인이 / AppleAuthSample에는 샘플코드가 있음을 볼 수 있다.

[플러그인 설정]

=>애플의 플랫폼과 프레임워크를 사용하려면 Xcode 프로젝트를 설정해주어야 한다.

 

[스크립트로 설정]

해당 방식은 Xcode 프로젝트의 설정의 변경을 해주는  ProjectCapabilityManager 을 사용한다.

 

이를 위해 사용하는  PostProcessing build 스크립트는 빌드후 호출되는 콜백함수이다.

  • 유니티 내부 특정 파일(특정 정보를 외부에서 수정 할 수 있게 빼놓은 데이터 텍스트)을 빌드 후에도 사라지지 않게 함
  • 0은 내부에서 쓰이는 order이기에 1 이상을 지정한다.
  • macOs에 설치된 유니티 에디터를 통해 실행되기에 Editor 폴더에 넣어준다
using AppleAuth.Editor;

public static class SignInWithApplePostprocessor
{
    [PostProcessBuild(1)]
    public static void OnPostProcessBuild(BuildTarget target, string path)
    {
        if (target != BuildTarget.iOS)
            return;

        var projectPath = PBXProject.GetPBXProjectPath(path);
        
        // Adds entitlement depending on the Unity version used
#if UNITY_2019_3_OR_NEWER
            var project = new PBXProject();
            project.ReadFromString(System.IO.File.ReadAllText(projectPath));
            var manager = new ProjectCapabilityManager(projectPath, "Entitlements.entitlements", null, project.GetUnityMainTargetGuid());
            manager.AddSignInWithAppleWithCompatibility(project.GetUnityFrameworkTargetGuid());
            manager.WriteToFile();
#else
            var manager = new ProjectCapabilityManager(projectPath, "Entitlements.entitlements", PBXProject.GetUnityTargetName());
            manager.AddSignInWithAppleWithCompatibility();
            manager.WriteToFile();
#endif
    }
}

+ mac os 를 위한 셋업도 추가해야 하는 듯 한데 이부분은 잘 모르겠음.

 

[메뉴얼 설정]

해당 방식은 여기를 참고하자.

 

[순서도]

애플 로그인을 위한 순서도이다 . 

[구현]

[초기화]

private IAppleAuthManager appleAuthManager;

void Start()
{
    ...
   // 현재 플랫폼이 지원한다면
   if (AppleAuthManager.IsCurrentPlatformSupported)
   {
       // Creates a default JSON deserializer, to transform JSON Native responses to C# instances
       var deserializer = new PayloadDeserializer();
       // Creates an Apple Authentication manager with the deserializer
       this.appleAuthManager = new AppleAuthManager(deserializer);    
   }
    ...
}

void Update()
{
    ...
    // Updates the AppleAuthManager instance to execute
    // pending callbacks inside Unity's execution loop
    if (this.appleAuthManager != null)
    {
        this.appleAuthManager.Update();
    }
    ...
}

[애플로 로그인]
=>유저의 이메일과 이름을 유저가 로그인하는 처음에 받는다. 추가 로그인 시도는 null emial/name을 받을것이다.

로그인과 이메일/이름에 대한 요청을 받을때 이렇게 한다.

var loginArgs = new AppleAuthLoginArgs(LoginOptions.IncludeEmail | LoginOptions.IncludeFullName);

this.appleAuthManager.LoginWithAppleId(
    loginArgs,
    credential =>
    {
        // Obtained credential, cast it to IAppleIDCredential
        var appleIdCredential = credential as IAppleIDCredential;
        if (appleIdCredential != null)
        {
            // Apple User ID
            // You should save the user ID somewhere in the device
            var userId = appleIdCredential.User;
            PlayerPrefs.SetString(AppleUserIdKey, userId);

            // Email (Received ONLY in the first login)
            var email = appleIdCredential.Email;

            // Full name (Received ONLY in the first login)
            var fullName = appleIdCredential.FullName;

            // Identity token
            var identityToken = Encoding.UTF8.GetString(
                appleIdCredential.IdentityToken,
                0,
                appleIdCredential.IdentityToken.Length);

            // Authorization code
            var authorizationCode = Encoding.UTF8.GetString(
                appleIdCredential.AuthorizationCode,
                0,
                appleIdCredential.AuthorizationCode.Length);

            // And now you have all the information to create/login a user in your system
        }
    },
    error =>
    {
        // Something went wrong
        var authorizationErrorCode = error.GetAuthorizationErrorCode();
    });

[로그인시 인증상태 알기]
=>Apple User id 가 유효한지 확인하는 메서드.

this.appleAuthManager.GetCredentialState(
    userId,
    state =>
    {
        switch (state)
        {
            case CredentialState.Authorized:
                // User ID is still valid. Login the user.
                break;
            
            case CredentialState.Revoked:
                // User ID was revoked. Go to login screen.
                break;
            
            case CredentialState.NotFound:
                // User ID was not found. Go to login screen.
                break;
        }
    },
    error =>
    {
        // Something went wrong
    });

https://gaeunhan.tistory.com/29