アカウントを端末へ保存
PFLogInViewControllerを使ってTwitterログインした際、アカウント情報を端末(設定アプリ)にも保存する方法を調べてみた。
発端
そもそもの発端は、Twitterにpostする画面としてSLComposeViewControllerを使おうとしたこと。そしてSLComposeViewControllerを使うには、端末に保存されたアカウントを必要とする。
前提
PFLogInViewControllerを使ってのTwitterログイン時、アカウントが端末に未登録の場合はWebViewベースの認証画面が表示され、アカウントを入力してログインする。
問題
この状態でSLComposeViewControllerを使おうとすると、端末へのアカウント登録を誘導するアラートが表示される。このアラートから設定アプリへ切り替えして登録することもできるが、ユーザーにとって登録が二度手間となるうえ、登録後に元のアプリへは自動で戻ってこれない。なのでユーザーが自分でアプリ切り替えをしないといけない。これらの動線は極力避けたかった。
アカウントの保存
ということで、PFLogInViewControllerでTwitterログインしたアカウント情報を使って端末にTwitterアカウントを保存する処理を調べて書いてみた。
まずはAccounts.frameworkをimportし、
1 |
#import <Accounts/Accounts.h> |
Twitterログイン後に以下処理を行う。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
ACAccountStore *accountStore = [[ACAccountStore alloc] init]; ACAccountType *accountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter]; ACAccount *account = [[ACAccount alloc] initWithAccountType:accountType]; ACAccountCredential *accountCredential = [[ACAccountCredential alloc] initWithOAuthToken:[[PFTwitterUtils twitter] authToken] tokenSecret:[[PFTwitterUtils twitter] authTokenSecret]]; account.username = [[PFTwitterUtils twitter] userId]; account.credential = accountCredential; [accountStore saveAccount:account withCompletionHandler:^(BOOL success, NSError *error) { if (error) { switch (error.code) { case ACErrorAccountAlreadyExists: DEBUG_LOG(@"error saving account: Account wasn't added because it already exists."); break; default: DEBUG_LOG(@"error saving account: %@", error.description); break; } } }]; |
これで端末上にアカウントが保存される。
ちなみに、同じ方法でFacebookアカウントも処理しようとしたが、
Error Domain=com.apple.accounts Code=7 “The application is not permitted to access Facebook accounts”
というエラーが発生して保存できない。
何かしらpermissionを与える方法があるのかどうか一通りネットでも調べてみたが、明確な情報はほとんどなく今のところお手上げ状態。
Facebookの基本的な認証システムを理解できていないのが要因かもしれない。