Parse.comはモバイルアプリにバックエンドを提供するBaaSの一つで、ログインやデータの保存などサーバーサイドでの処理が必要な機能を簡単に追加することができます。
これをCocos2d-xから使ってみます。サンプルプロジェクトは以下になります。
ntotani/cocos2dx-parsecom
Parse.comではiOS, Android用のSDKがそれぞれ提供されているので、Cocos2d-xではPlugin-Xからこれを利用します。Plugin-X自体の導入は別記事にあります。まずは設定とログインを書きます。
- (void) configDeveloperInfo : (NSMutableDictionary*) cpInfo
{
[Parse setApplicationId:[cpInfo objectForKey:@"ApplicationID"]
clientKey:[cpInfo objectForKey:@"ClientKey"]];
[PFTwitterUtils initializeWithConsumerKey:[cpInfo objectForKey:@"TwitterConsumerKey"] consumerSecret:[cpInfo objectForKey:@"TwitterConsumerSecret"]];
}
setApplicationId
でParse.comのIDとKeyを設定します。また、今回はTwitterでログインできるようにもしたいので、TwitterのアプリIDも設定します。
- (void) login
{
PFLogInViewController* vc = [[PFLogInViewController alloc] init];
vc.fields = PFLogInFieldsDefault | PFLogInFieldsTwitter;
vc.delegate = self;
[[AdsWrapper getCurrentRootViewController] presentViewController:vc animated:YES completion:nil];
}
PFLogInViewController
はParse.com標準のログイン画面です。fields
で表示させる要素を設定できます。また、プラグインの中からはRootViewControllerを直接参照できないので、AdsWrapper
のヘルパーメソッドを使います。
ログイン処理ができたので、これを呼び出します。
auto parse = dynamic_cast<ProtocolUser*>(PluginManager::getInstance()->loadPlugin("UserParse"));
parse->setDebugMode(true);
TUserDeveloperInfo devInfo;
devInfo["ApplicationID"] = "your_app_id";
devInfo["ClientKey"] = "your_client_key";
devInfo["TwitterConsumerKey"] = "your_consumer_key";
devInfo["TwitterConsumerSecret"] = "your_consumer_secret";
parse->configDeveloperInfo(devInfo);
parse->setActionListener(&s_parseListener);
//startScript("");
auto parse = dynamic_cast<ProtocolUser*>(PluginManager::getInstance()->loadPlugin("UserParse"));
parse->login();
applicationDidFinishLaunching
等でIDを設定し、login
を呼びます。今回はサンプルということで、接続待ち画面のPLAYボタンをタップしたタイミングでログインしています。
ビルドして実行します。ハマりどころとして、Plugin-Xを使用するためリンカフラグに-ObjC
を設定しますが、そのままだとParse.comのSDKがビルドできないのでFacebookSDKを追加してこれを回避します(詳細)。
ログイン画面が出れば成功です。ログインの結果はPFLogInViewControllerDelegate
で受け取ることができるので、これをUserActionListener
に流すとC++側で処理できます。
- (void)logInViewController:(PFLogInViewController *)logInController didLogInUser:(PFUser *)user
{
[UserWrapper onActionResult:self withRet:kLoginSucceed withMsg:user.username];
}
- (void)logInViewController:(PFLogInViewController *)logInController didFailToLogInWithError:(NSError *)error
{
[UserWrapper onActionResult:self withRet:kLoginFailed withMsg:[error localizedDescription]];
}
- (void)logInViewControllerDidCancelLogIn:(PFLogInViewController *)logInController
{
[UserWrapper onActionResult:self withRet:kLoginFailed withMsg:@"cancel"];
}
class ParseListener : public UserActionListener
{
void onActionResult(ProtocolUser* pPlugin, UserActionResultCode code, const char* msg)
{
if (code == UserActionResultCode::kLoginSucceed) {
log("parse login succeed: %s", msg);
}
}
};
static ParseListener s_parseListener;