新浪微博發送訊息和授權機制原理(WeiboSDK)

來源:互聯網
上載者:User

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在你的新浪開發人員帳號裡有。



2.授權,通過授權我們可以在使用者未安裝用戶端的情況下關注指定微博。

授權主要是為了得到:userID,accessToken,有了accessToken我們就可以訪問新浪weibo的API了http://open.weibo.com/wiki/%E5%BE%AE%E5%8D%9AAPI



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類庫



聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.