DRYな備忘録

Don't Repeat Yourself.

【iOS】デバイスのTwitterアカウント情報へアクセスする

ゴール

  • Twitterアカウントへのアクセス許可要求ダイアログを出す
  • 許可されたらTwitterアカウント名、IDなどを取得する

f:id:otiai10:20140809220751j:plain

記録

まず空のアプリつくる

  1. Xcode起動
  2. SingleViewApplicationを選択してCreate New
  3. 実機に向けてrunして真っ白画面出ることを確認

詳細割愛

参考

必要なframeworkを追加する

ここで+

f:id:otiai10:20140809214323j:plain

Accounts.frameworkを検索して追加

f:id:otiai10:20140809214332j:plain

launchと同時でよいので

AppDelegate.mdidFinishLaunchingWithOptionsに直で以下を書く

f:id:otiai10:20140809215351j:plain

diff --git a/iTwitterAccoutSample/TwitterAccoutSampleAppDelegate.m b/iTwitterAccoutSample/TwitterAccoutSampleAppDelegate.m
index a97d4ea..f044e56 100644
--- a/iTwitterAccoutSample/TwitterAccoutSampleAppDelegate.m
+++ b/iTwitterAccoutSample/TwitterAccoutSampleAppDelegate.m
@@ -8,11 +8,42 @@
 
 #import "TwitterAccoutSampleAppDelegate.h"
 
+// (1) importしまーす
+#import <Accounts/Accounts.h>
+
 @implementation TwitterAccoutSampleAppDelegate
 
 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
 {
     // Override point for customization after application launch.
+
+    // (2) とりあえずここに書いちゃおう
+    ACAccountStore *store = [ACAccountStore new];
+    ACAccountType *type = [store accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
+    // optionsって何渡せばいいか分からんので、とりあえず空のやつでいいや
+    // NSDictionary *options = @{};
+    // しらべた感じ、何も要らないならnilを渡せって言われた
+    
+    // (3) ユーザに許可要求する
+    [store requestAccessToAccountsWithType:type options:nil completion:^(BOOL granted, NSError *error) {
+        if (! granted) {
+            NSLog(@"%@", error);
+            return;
+        }
+        // (4) 許可されたので、取得する
+        NSArray *accounts = [store accountsWithAccountType:type];
+        // (5) 許可されたけど、無かったりして
+        if (accounts.count < 1) {
+            return;
+        }
+        // (6) とりあえず最初のやつで
+        ACAccount *account = accounts[0];
+        NSLog(@"取得できたやつ %@", NSStringFromClass([account class]));
+        NSLog(@"ユーザネーム? %@", [account username]);
+        NSLog(@"ユーザID? %@", [[account valueForKey:@"properties"] objectForKey:@"user_id"]);
+        return;
+    }];
+    
     return YES;
 }

実行してみる

ダイアログが出た

f:id:otiai10:20140809220751j:plain

許可すると…

Xcodeのコンソールに

f:id:otiai10:20140809221958j:plain

バッチグーっぽい

詰まったところ

  • requestAccessToAccountsWithTypeの第二引数optionsに何渡していいか分からん
    • のでNSDictionary *options = @{}として、空dictionaryを渡した
    • NSInvalidArgumentExceptionで叱られる
    • 公式ドキュメント見ると
    • 「if the account type does not require an options dictionary, the options parameter must be nil.」と書いてある
    • nil渡して解決

雑感

  • ObjectiveCの文法とかAppleの証明書とか色々とっつきにくいけれど慣れれば良い感じ
  • クラスやそのメソッドについての解説はやっぱり公式が一番良いと感じた
  • 証明書とか申請関係は野良ドキュメントの方が親切

DRYな備忘録

本気ではじめるiPhoneアプリ作り Xcode 8.x+Swift 3.x対応 (ヤフー黒帯シリーズ)

本気ではじめるiPhoneアプリ作り Xcode 8.x+Swift 3.x対応 (ヤフー黒帯シリーズ)