码迷,mamicode.com
首页 > 其他好文 > 详细

新浪微博发送消息和授权机制原理(WeiboSDK)

时间:2014-06-29 23:31:40      阅读:435      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   http   color   get   

1.首先是在微博发送消息,对于刚开始做weibo发送消息的初学者会有一个误区,那就是会认为需要授权后才可以发送消息,其实发送消息只需要几行代码就可以实现了,非常简单,不需要先授权再发送消息,因为weibosdk已经帮我们封装好了。(此情况需要用户安装客户端)

发送消息流程为:点击发送消息按键----SDK会自动帮我们判断用户是否安装了新浪微博客户端--如果未安装弹出安装提示----如果安装直接跳转到sina微博客户端进行发送----发送成功后自动跳回原应用程序。

1)在AppDelegate中注册sdk, AppDelegate需要实现WeiboSDKDelegate

AppDelegate.h
@interface AppDelegate : UIResponder <UIApplicationDelegate, WeiboSDKDelegate>
{...

AppDelegate.m

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

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

2)拼接消息对象WBMessageObject,并发送消息[WeiboSDK sendRequest:request];

WBSendMessageToWeiboRequest *request = [WBSendMessageToWeiboRequest requestWithMessage:[self messageToShare]];
    request.userInfo = @{@"ShareMessageFrom": @"SendMessageToWeiboViewController",
                         @"Other_Info_1": [NSNumber numberWithInt:123],
                         @"Other_Info_2": @[@"obj1", @"obj2"],
                         @"Other_Info_3": @{@"key1": @"obj1", @"key2": @"obj2"}};
    //    request.shouldOpenWeiboAppInstallPageIfNotInstalled = NO;
    
    [WeiboSDK sendRequest:request];//这句就可以发送消息了,不需要先授权

- (WBMessageObject *)messageToShare
{
    WBMessageObject *message = [WBMessageObject message];
    
    if (self.textSwitch.on)
    {
        message.text = @"测试通过WeiboSDK发送文字到微博!";
    }
    
    if (self.imageSwitch.on)
    {
        WBImageObject *image = [WBImageObject object];
        image.imageData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"image_1" ofType:@"jpg"]];
        message.imageObject = image;
    }

    if (self.mediaSwitch.on)
    {
        WBWebpageObject *webpage = [WBWebpageObject object];
        webpage.objectID = @"identifier1";
        webpage.title = @"分享网页标题";
        webpage.description = [NSString stringWithFormat:@"分享网页内容简介-%.0f", [[NSDate date] timeIntervalSince1970]];
        webpage.thumbnailData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"image_2" ofType:@"jpg"]];
        webpage.webpageUrl = @"http://sina.cn?a=1";
        message.mediaObject = webpage;
    }
    
    return message;
}

重要:如果程序发送完消息无法跳回原应用的话是因为在plist文件中没有配置URL Types,appKey在你的新浪开发者帐号里有。

bubuko.com,布布扣


2.授权,通过授权我们可以在用户未安装客户端的情况下关注指定微博。

授权主要是为了得到:userID,accessToken,有了accessToken我们就可以访问新浪weibo的API了http://open.weibo.com/wiki/%E5%BE%AE%E5%8D%9AAPI

bubuko.com,布布扣


response.userInfo对象就是我们要的东西

1)当点击授权

//com.sina.weibo.SNWeiboSDKDemo
#define kAppKey         @"2045436852"
#define kRedirectURI    @"http://www.sina.com"

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

2)上面的代码会弹出一个授权窗口,用户可以输入用户名和密码,输入完成或者关闭窗口程序会自动调用AppDelegate类中的didReceiveWeiboResponse方法。

如果你的程序弹出授权窗口还没有等用户输入帐号密码就自动关闭了关马上调用了didReceiveWeiboResponse方法,这时返回的statusCode为-3,那么说明你应用授权失败了,此时需要设置你应用的Bundle identifier,例如:com.sina.weibo.SNWeiboSDKDemo

- (void)didReceiveWeiboResponse:(WBBaseResponse *)response
{
    if ([response isKindOfClass:WBSendMessageToWeiboResponse.class])
    {
        NSString *title = @"发送结果";
        NSString *message = [NSString stringWithFormat:@"响应状态: %d\n响应UserInfo数据: %@\n原请求UserInfo数据: %@",(int)response.statusCode, response.userInfo, response.requestUserInfo];
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                        message:message
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        //[alert show];
        [alert release];
    }
    else if ([response isKindOfClass:WBAuthorizeResponse.class])
    {
        NSString *title = @"认证结果";
        NSString *message = [NSString stringWithFormat:@"响应状态: %d\nresponse.userId: %@\nresponse.accessToken: %@\n响应UserInfo数据: %@\n原请求UserInfo数据: %@",(int)response.statusCode,[(WBAuthorizeResponse *)response userID], [(WBAuthorizeResponse *)response accessToken], response.userInfo, response.requestUserInfo];
        
        NSLog(@"didReceiveWeiboResponse message = %@",message);
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                        message:message
                                                       delegate:nil
                                              cancelButtonTitle:@"确定"
                                              otherButtonTitles:nil];
        
        self.wbtoken = [(WBAuthorizeResponse *)response accessToken];
        
        [alert show];
        [alert release];
    }
}
3)得到response.userInfo对象,我们就可以得到对象里面的userID和accessToken数据了,使用他们访问新浪接口http://open.weibo.com/wiki/%E5%BE%AE%E5%8D%9AAPI


#define HOSTURL @"api.weibo.com"
NSString *accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:SINA_ACCESS_TOKEN_KEY];
    
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setObject:accessToken forKey:@"access_token"];
    [dic setObject:userId forKey:@"uid"];
    [dic setObject:screenName forKey:@"screen_name"];
    NSString *path = @"2/friendships/create.json";
    if (flag != 0) {
        path = @"2/friendships/destroy.json";
    }
    

    
    [HttpBaseModel getDataResponseHostName:HOSTURL Path:path params:dic httpMethod:@"POST" onCompletion:^(NSData *responseData){
        
        NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
        NSLog(@"responseString = %@", responseString);
        
        SBJSON *json = [[SBJSON alloc] init];
        NSError *error = nil;
        NSDictionary *jsonDic = [json objectWithString:responseString error:&error];
        
        User *user = [User getUserFromJsonDic:jsonDic];
        isSuccess(YES, user);
        
    } onError:^(NSError *error){
        isSuccess(NO, nil);
    }];

别问我怎么post访问接口,请百度搜索:ASIHTTPRequest类库



新浪微博发送消息和授权机制原理(WeiboSDK),布布扣,bubuko.com

新浪微博发送消息和授权机制原理(WeiboSDK)

标签:des   style   blog   http   color   get   

原文地址:http://blog.csdn.net/coooliang/article/details/35614111

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!