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?

More than 1 year has passed since last update.

Parse Server Java SDKの使い方(Kotlinでのユーザー管理)

Posted at

ニフクラ mobile backendは3月末で終了します

ニフクラ mobile backendからの移行先として、お勧めしているのがParse Serverです。設計思想が近く、変更するコード量が少なく済むのではないかと思います。

Parse ServerではAndroid向けにSDKを提供していますが、言語はJavaのみとなっています。そのため、Kotlin向けには、Java SDKの内容を翻訳しながら実装する必要があります。そこで、本記事にて、各機能の使い方を解説します。今回はユーザー管理(認証)について紹介します。

Android SDKのインストール

Android SDKのインストールは幾つかの設定が必要です。

settings.gradleの修正

プロジェクトルートにある settings.gradle を修正します。

dependencyResolutionManagement {
    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
    repositories {
        google()
        mavenCentral()
				// 以下を追加
        maven {
            url "https://jitpack.io"
        }
    }
}

app/build.gradleの修正

app以下にある build.gradle を修正します。

dependencies {
	// 以下を追加
	implementation "com.github.parse-community.Parse-SDK-Android:parse:4.2.1"
}

バージョンはインストールするタイミングによって異なりますが、現在は以下です。

AndroidManifest.xmlの修正

開発中で、ローカルのParse Serverを使う場合には、以下の設定が必要です。

<application
	android:usesCleartextTraffic="true" <!-- 追加 -->
>

初期化

SDKの初期化は MainActivity にて行います。Androidはエミュレーターなので、 localhost:1337 ではなく、 192.168.0.2:1337 などがParse ServerのURLになるでしょう。

オフライン対応する際には .enableLocalDataStore() を追加します。これがないと、オフライン時にデータ操作できないので注意してください。

import com.parse.Parse

class MainActivity : AppCompatActivity() {

    private lateinit var appBarConfiguration: AppBarConfiguration
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Parse.initialize(
            Parse.Configuration.Builder(this)
                .applicationId("appId")
                .clientKey("clientKey")
								.enableLocalDataStore()
                .server("http://your_parse_server/parse/")
                .build()
        )
				// 省略
		}
}

ユーザー登録

ユーザー登録の基本はユーザーIDとパスワードです。以下のコードで登録できます。

val user = ParseUser()
user.username = "ncmb"
user.setPassword("password")
user.email = "email@example.com"
user.put("phone", "650-253-0000")

user.signUpInBackground { e ->
		if (e == null) {
				Log.d("DEBUG", "Sign in as -> " + user.objectId)
		} else {
				Log.d("DEBUG", e.message ?: "")
		}
}

同期処理用に signUp メソッドもあります。

try {
		user.signUp()
		Log.d("DEBUG", "Sign in as -> " + user.objectId)
} catch (e: ParseException) {
		Log.d("DEBUG", e.message ?: "")
}

ログイン

ログインは以下のコードで行います。

ParseUser.logInInBackground("ncmb", "password") { user, e ->
		if (e == null) {
				Log.d("DEBUG", "Logged in as -> " + user.objectId)
		} else {
				Log.d("DEBUG", e.message ?: "")
		}
}

こちらもユーザ登録と同じく、同期処理用に logIn メソッドがあります。

try {
		val user = ParseUser.logIn("ncmb", "password")
		Log.d("DEBUG", "Logged in as -> " + user.objectId)
} catch (e: ParseException) {
		Log.d("DEBUG", e.message ?: "")
}

メールアドレス認証

メールアドレスを使う場合には、 emailVerified というフィールドを追加して、独自に実装する必要があるようです。

ログイン判定

ログイン判定は以下のコードで行います。

val currentUser = ParseUser.getCurrentUser()
if (currentUser != null) {
		Log.d("DEBUG", "Logged in as -> " + currentUser.objectId)
} else {
		Log.d("DEBUG", "Not logged in")
}

ログアウト

ログアウトは以下のコードで行います。

ParseUser.logOutInBackground { e ->
		if (e == null) {
				Log.d("DEBUG", "Logged out")
		} else {
				Log.d("DEBUG", e.message ?: "")
		}
}

同期処理用に logOut メソッドもあります。


try {
		ParseUser.logOut()
		Log.d("DEBUG", "Logged out")
} catch (e: ParseException) {
		Log.d("DEBUG", e.message ?: "")
}

匿名認証

NCMBでいう匿名認証も、Parse Serverに用意されています。以下のコードで実装できます。

ParseAnonymousUtils.logIn { user, e ->
		if (e == null) {
				Log.d("DEBUG", "Logged in as -> " + user.objectId)
		} else {
				Log.d("DEBUG", e.message ?: "")
		}
}

ソーシャル認証

ソーシャル認証用に、以下のクラスが用意されています。

  • ParseFacebookUtils
  • ParseTwitterUtils

他の認証方法については専用のクラスがなかったので、 ParseUser.logInWithInBackground を使って実装する必要があります。こちらは同期処理用のメソッドがありませんでした。

まとめ

Parse ServerとNCMBのデータストア操作は、Android SDK同士では大きくは異なりません。載せ替える際には、大きなコードにはならなそうです。基本の認証は問題なさそうですが、メールアドレスログインがないこと、FacebookとTwitter以外のソーシャルログインがないのが気になりました。

データの管理方法などはParse ServerとNCMBで似ています。他のmBaaSと比べると、全体の修正量はそこまで多くないと思われます。載せ替え先として検討に挙げてください。

Android Developers Guide | Parse

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?