LoginSignup
9
10

More than 5 years have passed since last update.

WeiboSDKでiOSからWeiboにログイン&ツイート

Posted at

中国でソーシャルを絡めたiPhoneアプリを展開

基本的に、アプリは日本向けに開発するのだけど、このアプリ中国でもいけるのでは?となったりする。。けど、中国だとFacebookやTwitterは使えないので、ソーシャルと絡めたい場合は、中国語版Facebook&TwitterともいえるWeibo(新浪微博)を使わざるを得ない。ということで、iOS&WebioSDKの使い方メモです。

この記事の対象者

  • Facebook / Twitterなどソーシャル連携した日本向けアプリの中国展開を考えている人。
  • ユーザー数5億人ともいわれるWeiboにアプリで切り込みたいと考えている人。
  • (中国語を勉強しながらアプリも開発したい人。)

Webio実装の流れ

まずは全体の流れとしては下記の通り。

Weiboへのアカウント/開発者登録やアプリ登録は済んでいるものとします。
まだの人は右記サイト参照 ⇒ iOSからWeibo(微博)にログイン〜ツイートしてみる

weibo-ios-flow

追加・変更するファイル一覧

  1. Prefix.pch
  2. AppDelegate.h
  3. AppDelegate.m
  4. WeiboViewController.m
  5. WeiboViewController.m

WeiboSDKの初期設定

1. 「Prefix.pch」

アプリキーとコールバックURIをそれぞれ定義しておきます。どちらもWeiboのアプリ管理ページで設定・取得できます。

#define kAppKey @"アプリキー"
#define kRedirectURI @"https://api.weibo.com/oauth2/default.html" // アプリのコールバック設定と合わせる。

2. AppDelegate.h


#import <UIKit/UIKit.h>
#import "WeiboSDK.h" // 追加

@interface AppDelegate : UIResponder <UIApplicationDelegate, WeiboSDKDelegate> // デリゲート追加

@property (strong, nonatomic) UIWindow *window; 
@property (strong, nonatomic) NSString *wbtoken; // 追加 (トークン用)

@end

3. AppDelegate.m

WebioSDKを設定し、デリゲートメソッドを3つ追加します。

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    [WeiboSDK enableDebugMode:YES]; // 追加
    [WeiboSDK registerApp:kAppKey]; // 追加

    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    [self.window makeKeyAndVisible];

    WeiboViewController* weiboViewController = [[WeiboViewController alloc] init];
    self.window.rootViewController = weiboViewController;

    return YES;
}

pragma - Weibo SDK delegate methods

- (void)didReceiveWeiboRequest:(WBBaseRequest *)request
{
    if ([request isKindOfClass:WBProvideMessageForWeiboRequest.class])
    {
        WeiboViewController *controller = [[WeiboViewController alloc] init];
        [self.window.rootViewController presentViewController:controller animated:YES completion:nil];
    }
}

- (void)didReceiveWeiboResponse:(WBBaseResponse *)response
{
    if ([response isKindOfClass:WBSendMessageToWeiboResponse.class])
    {
        NSString *title = @"发送结果";
        NSString *message = [NSString stringWithFormat:@"响应状态: %d\n响应UserInfo数据: %@\n原请求UserInfo数据: %@",
                                                       response.statusCode, response.userInfo, response.requestUserInfo];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                        message:message
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        [alert show];
    }
    else if ([response isKindOfClass:WBAuthorizeResponse.class])
    {
        NSString *title = @"认证结果";
        NSString *message = [NSString stringWithFormat:@"响应状态: %d\nresponse.userId: %@\nresponse.accessToken: %@\n响应UserInfo数据: %@\n原请求UserInfo数据: %@",
                                                       response.statusCode, [(WBAuthorizeResponse *)response userID], [(WBAuthorizeResponse *)response accessToken], response.userInfo, response.requestUserInfo];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                        message:message
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];

        self.wbtoken = [(WBAuthorizeResponse *)response accessToken];

        [alert show];
    }
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    return [WeiboSDK handleOpenURL:url delegate:self];
}

これでひとまず、Weiboの基本設定完了。次にWeiboでのログインとツイートを実装します。

Weiboへのログイン&ツイート実装

WeiboViewControllerを作成します。ここでログイン&ツイートボタンとそれぞれの処理を実装します。コードは以下の通り。

4. WeiboViewController.h

#import <UIKit/UIKit.h>

@interface WeiboViewController : UIViewController

@end

5. WeiboViewController.m

#import "WeiboViewController.h"
#import "WeiboSDK.h"
#import "AppDelegate.h"

@interface WeiboViewController () <WBHttpRequestDelegate>

@end

@implementation WeiboViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.

    self.view.backgroundColor = UIColor.grayColor;

    // ログインボタン
    UIButton *ssoButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [ssoButton setTitle:@"ログイン" forState:UIControlStateNormal];
    [ssoButton addTarget:self action:@selector(ssoButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    ssoButton.frame = CGRectMake(20, 250, 280, 50);
    [self.view addSubview:ssoButton];

    UIButton *tweetButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [tweetButton setTitle:@"つぶやく" forState:UIControlStateNormal];
    [tweetButton addTarget:self action:@selector(tweetButtonPressed) forControlEvents:UIControlEventTouchUpInside];
    tweetButton.frame = CGRectMake(20, 370, 280, 50);
    [self.view addSubview:tweetButton];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)ssoButtonPressed
{
    WBAuthorizeRequest *request = [WBAuthorizeRequest request];
    request.redirectURI = kRedirectURI;
    request.scope = @"all";
    request.userInfo = @{@"SSO_From": @"WeiboViewController",
            @"Other_Info_1": [NSNumber numberWithInt:123],
            @"Other_Info_2": @[@"obj1", @"obj2"],
            @"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};
    [WeiboSDK sendRequest:request];
}

- (void)tweetButtonPressed
{
    NSLog(@"*** tweetButtonPressed ");
    AppDelegate *myDelegate =(AppDelegate*)[[UIApplication sharedApplication] delegate];
    [WBHttpRequest requestWithAccessToken:myDelegate.wbtoken
                                      url:@"https://api.weibo.com/2/statuses/update.json"
                               httpMethod:@"POST"
                                   params:@{@"status":@"Hello World"}
                                 delegate:self
                                  withTag:nil];
}

- (void)request:(WBHttpRequest *)request didFinishLoadingWithResult:(NSString *)result
{
    NSString *title = nil;
    UIAlertView *alert = nil;

    title = @"成功しました。";
    alert = [[UIAlertView alloc] initWithTitle:title
                                       message:[NSString stringWithFormat:@"%@",result]
                                      delegate:nil
                             cancelButtonTitle:@"OK"
                             otherButtonTitles:nil];
    [alert show];
}

- (void)request:(WBHttpRequest *)request didFailWithError:(NSError *)error;
{
    NSString *title = nil;
    UIAlertView *alert = nil;

    title = @"失敗しました。";
    alert = [[UIAlertView alloc] initWithTitle:title
                                       message:[NSString stringWithFormat:@"%@",error]
                                      delegate:nil
                             cancelButtonTitle:@"OK"
                             otherButtonTitles:nil];
    [alert show];
}

@end

上記のコードはGithubにもUP。 ⇒ kuman/ios-weibo-test

テスト

シミュレーターを起動し、「ログイン」ボタンを押すとWebioのブラウザベースのWeiboログインフォームが表示される。ログイン後に「つぶやく」ボタンをタッチするとWeibo上に"Hello World!"とツイートされる。

MEMO

  • ドキュメントが中国語が辛い。
  • API操作はWeiboWikiのドキュメントを見れればまぁいける。
  • ログイン後にコールバックでアプリに戻ってくれず少しはまる。(Weibo管理画面のバンドルID/コールバック設定やXcode上のpListなど見直して解決)
  • Google ChromeだとWeiboの新規登録ができなかったのでFirefoxで登録した。

参考

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