Principles of message sending and authorization on Sina Weibo (weibosdk)

Source: Internet
Author: User

1. the first is to send messages on Weibo. There is a misunderstanding for beginners who are sending messages at the beginning of Weibo, that is, they will think that messages can be sent only after authorization, in fact, only a few lines of code are required to send messages, which is very simple,You do not need to authorize before sending messages.Because weibosdk has been encapsulated for us. (In this case, you need to install the client)

The message sending process is as follows: click the send message button-the SDK will automatically help us determine whether the user has installed the Sina Weibo client-if not installed, the installation prompt will pop up-if the installation is directly redirected to the Sina Weibo client for sending-automatically after the sending is successful jump back to the original application.

1) register the SDK in appdelegate. appdelegate must implement weibosdkdelegate.

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

Appdelegate. m-(bool) Application :( uiapplication *) Application dictionary :( nsdictionary *) launchoptions {// register the 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) splice the message object wbmessageobject and send the message [weibosdk sendrequest: request];

Wbsendmessagetoweibo orequest * request = [wbsendmessagetoweibo orequest 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]; // The message can be sent without authorization.

-(Wbmessageobject *) messagetoshare {wbmessageobject * message = [wbmessageobject message]; If (self. textswitch. On) {message. Text = @ "test using weibosdk to send text to Weibo! ";} 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 = @ "share webpage title"; webpage. description = [nsstring s Tringwithformat: @ "share webpage content overview-%. 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 ;}

Important: if the application cannot jump back to the original application after sending the message, it is because the URL types is not configured in the plist file, and the appkey is included in your sina developer account.



2. Authorization. With authorization, users can follow the specified Weibo account without installing the client.

Authorization is mainly to get: userid, accesstoken, with accesstoken we can access Sina Weibo API http://open.weibo.com/wiki/%E5%BE% AE %E5%8D%9AAPI



Response. userinfo object is what we want

1) Click authorize

//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) the above Code will pop up an authorization window. You can enter the user name and password. After the input is complete or the window is closed, the program will automatically call the didreceiveweibo oresponse method in the appdelegate class.

If the authorization window in your program pops up, And the didreceiveweibo oresponse method is called immediately after the user enters the account password, the statuscode returned is-3, which indicates that your application authorization has failed, in this case, you need to setBundle identifierFor example: COM. Sina. Weibo. snweibosdkdemo

-(Void) didreceiveweibo oresponse :( wbbaseresponse *) response {If ([Response iskindofclass: wbsendmessagetoweibo oresponse. class]) {nsstring * Title = @ "sending result"; nsstring * message = [nsstring stringwithformat: @ "response status: % d \ n response userinfo data: % @ \ n original request userinfo data: % @ ", (INT) response. statuscode, response. userinfo, response. requestuserinfo]; uialertview * Alert = [[uialertview alloc] initwithtitle: Title message: Message delegate: Nil cancelbuttontitle: @ "OK" failed: Nil]; // [alert show]; [alert release];} else if ([Response iskindofclass: wbauthorizeresponse. class]) {nsstring * Title = @ "Certification result"; nsstring * message = [nsstring stringwithformat: @ "response status: % d \ nresponse. userid: % @ \ nresponse. accesstoken: % @ \ n response userinfo data: % @ \ n original request userinfo data: % @ ", (INT) response. statuscode, [(wbauthorizeresponse *) response userid], [(wbauthorizeresponse *) response accesstoken], response. userinfo, response. requestuserinfo]; nslog (@ "Response Message = % @", message); uialertview * Alert = [[uialertview alloc] initwithtitle: Title message: Message delegate: Nil cancelbuttontitle: @ "OK" otherbuttontitles: Nil]; self. wbtoken = [(wbauthorizeresponse *) response accesstoken]; [alert show]; [alert release];}
3) Get the response. userinfo object. We can Get the userid and accesstoken data in the object and use them to access the Sina interface.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);    }];

Don't ask me how to access the post interface. Please search Baidu for: asihttprequest class library



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.