LoginSignup
9
8

More than 5 years have passed since last update.

ACAccountを汎用的に取得するメソッド

Posted at

iOS5からTwitterアカウントにアクセス出来るようになりましたが、複数アカウントがある場合、選択するためのUIが必要になってきます。
UIはアプリごとに差異があるため、毎回一から実装し直しだったりします。

今回はUI部分はカスタマイズ性を残しつつ、取得処理をカプセル化できるような処理を考えてみました。
メソッドは以下のようになります。(エラー処理は端折ってます)

typedef void (^STACAccountInnerCallback)(ACAccount *account);
typedef void (^STACAccountCallback)(NSArray *accounts, STACAccountInnerCallback innerCallback);

+ (void)requestACAccountWithAccountTypeIdentifier:(NSString *)accountTypeIdentifier options:(NSDictionary *)options callback:(STACAccountCallback)callback completion:(void (^)(ACAccount *, NSError *))completion
{
    //省略
    [accountStore requestAccessToAccountsWithType:accountType options:options completion:^(BOOL granted, NSError *error) {
        if (granted) {
            NSArray *accounts = [accountStore accountsWithAccountType:accountType];
            //省略 一つの場合はそのままcompletionに渡す
            //複数アカウントの場合
            callback(accounts, ^(ACAccount *account) {
                completion(account, nil);
            });
        }
    }];
}

利用するときはこんな感じです。
BlocksKit推奨です。

//コールバックブロック内に任意の選択UIを実装する
STACAccountCallback callback = ^(NSArray *accounts, STACAccountInnerCallback innerCallback) {
    dispatch_async(dispatch_get_main_queue(), ^{
        //今回はUIActionSheetを利用
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:@"Select"];
        for (ACAccount *account in accounts) {
            [actionSheet addButtonWithTitle:account.username handler:^{
                //選択されたアカウントを引数にブロックを呼び出す
                innerCallback(account);
            }];
        }

        UIView *view = [[[UIApplication sharedApplication] delegate] window];
        [actionSheet showInView:view];
    });
};


[Hoge requestACAccountWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter
                                        options:nil
                                       callback:callback
                                     completion:^(ACAccount *account, NSError *error) {
                                          NSLog(@"%@", account);
                                      }];

このメソッドを利用することでアカウントが一つでも複数の場合でも、completionブロックでアカウントを取得した後の処理を実装することができます。
また、UI部分を外出し出来たので色々な環境で利用出来ると思います。
一応、Facebookのアカウント取得も同じメソッドで取得出来ます。

9
8
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
9
8