IOS Sina Weibo client demo practices (I) oauth2.0 Certification

Source: Internet
Author: User

Continue to learn about iOS, Sina Weibo demo of this exercise.

This exercise program is implemented in multiple parts. The following is the first article -- oauth2.0 certification.

The following briefly describes the preparations before program development. First, you must create a mobile app on the Sina developer platform to obtain the key and secret, note that you must edit the authorization callback page of oauth2.0 authorization settings in the advanced information in the application information of the Management Center.

Two APIs are used for authentication: Request Authorization and authorization. (The link address is: http://open.weibo.com/wiki/Oauth2/authorize and http://open.weibo.com/wiki/OAuth2/access_token ). What is the relationship between the two? First, you must use authorize to obtain the access token. Access
Token is a required parameter for future API calls. The two API documents show that the access token call parameters contain the code parameters returned after authorize is called (For details, refer to the document ).

The following describes the authorize API.

https://api.weibo.com/oauth2/authorize?client_id=2909579077&redirect_uri=http://www.baidu.com&response_type=code&display=mobile&state=authorize

The following explains how to pass parameters in this URL. The first step is to add a question mark after the authentication URL: https://api.weibo.com/oauth2/authorize? Then each parameter and value are passed. Each parameter is separated.

Parameter description:

Here, client_id is the key you applied to create the application. redirect_uri is the authorization callback page mentioned above in the authorization settings. Ensure that the two are consistent. Enter the code in response_type, this code is a string of code that will be returned during authorization. This string of code will be used as a parameter value in the second API call (Note: This code is changed, that is to say, each authorization is dynamically changed. The access token we will obtain later is fixed.) Of course, you can also enter it as a token, the URL returned by the authorization includes access
Token (which will be detailed below); fill in Mobile (Mobile Terminal application) in display; the parameter "state" is optional, that is, or can be omitted, this parameter is included in the data returned by the authorization. With this URL, you can load an authorization page in Weibo view. You can enter this URL in a browser to verify whether the URL is correct.

After authorization, the following parameters are obtained:

Return Value Field Field Type Field description
Code String Used to call access_token to obtain the authorized access token.
State String If a parameter is passed, the parameter is returned.

The following is the code for loading webview. The authorization page is displayed through the following code.

- (void)viewDidLoad{    [super viewDidLoad];// Do any additional setup after loading the view, typically from a nib.    NSString *urlString = @"https://api.weibo.com/oauth2/authorize?client_id=2909579077&redirect_uri=http://www.baidu.com&response_type=code&display=mobile&state=authorize";    NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:urlString]];    [self.webView setDelegate:self];    [_webView loadRequest:request];    }

This is probably the case with authorize above. Now the question is, how can we get the returned data? From the examples in the official API documentation, we know that after authorization, it will be redirected to another URL, the URL contains the data to be returned (the focus is on the Code parameter ).

Next, I will post a piece of code, which contains the URL for getting redirection. Capture the code parameter value from the URL, add the code parameter value to the access_token API, and call it, obtain the returned parameters after the call, process the returned parameters, and then obtain the access_token. (This code has a lot of problems to deal)

For details about the URL called by the second API access token, refer to the official documentation and the URL of the first API.

-(Bool) webview :( uiwebview *) webview shouldstartloadwithrequest :( nsurlrequest *) Request navigationtype :( uiwebviewnavigationtype) navigationtype {nsurl * backurl = [request URL]; // URL nsstring * backurlstring = [backurl absolutestring]; // determine whether the URL returned by an authorized call is if ([backurlstring hasprefix: @ "http://www.baidu.com /? "]) {Nslog (@" Back URL string: % @ ", backurlstring); // locate the range nsange rangeone with" code = "; rangeone = [backurlstring rangeofstring: @ "code ="]; // determine the range of the value of the Code parameter according to its "code =" range = nsmakerange (rangeone. length + rangeone. location, backurlstring. length-(rangeone. length + rangeone. location); // obtain the code value nsstring * codestring = [backurlstring substringwithrange: range]; nslog (@ "code =: % @", codestring ); // Access token calls the URL's string nsmutablestring * mustring = [[nsmutablestring alloc] initwithstring: @ "https://api.weibo.com/oauth2/access_token? Client_id = 2909579077 & client_secret = Response & grant_type = authorization_code & redirect_uri = http://www.baidu.com & code = "]; [mustring appendstring: codestring]; nslog (@" access token URL: % @", mustring); // Step 1: Create URL nsurl * urlstring = [nsurl urlwithstring: mustring]; // Step 2: Create a request for nsmutableurlrequest * request = [[nsmutableurlrequest alloc] initwithurl: urlstring cachepolicy: nsurlrequestuseprotocolcachepolicy timeoutinterval: 10]; [Request sethttpmethod: @ "Post"]; // set the request method to post, the default value is get nsstring * STR = @ "type = focus-c"; // set the nsdata * Data = [STR datausingencoding: nsutf8stringencoding]; [Request sethttpbody: Data]; // Step 3: connect to the server nsdata * received = [nsurlconnection sendsynchronousrequest: Request returningresponse: Nil error: Nil]; nsstring * str1 = [[nsstring alloc] initwithdata: received encoding: nsutf8stringencoding]; nslog (@ "Back string: % @", str1); // How To Get access_token nsdictionary * dictionary = [str1 objectfromjsonstring] From str1; nslog (@ "access token is: % @", [dictionary objectforkey: @ "access_token"]);} return yes ;}

Result of the program running

2013-04-14 15:46:14.798 OAuthDemo[350:c07] back url string :http://www.baidu.com/?state=authorize&code=a6146547f981199c07348837b0629d5d2013-04-14 15:46:14.799 OAuthDemo[350:c07] code = :a6146547f981199c07348837b0629d5d2013-04-14 15:46:14.799 OAuthDemo[350:c07] access token url :https://api.weibo.com/oauth2/access_token?client_id=2909579077&client_secret=90184f4606fd04f449131ea4fbdb74c4&grant_type=authorization_code&redirect_uri=http://www.baidu.com&code=a6146547f981199c07348837b0629d5d2013-04-14 15:46:15.059 OAuthDemo[350:c07] Back String :{"access_token":"2.00QF7O9Cn7SuKDdeaf7e6529rPILeC","remind_in":"157679999","expires_in":157679999,"uid":"2249439934"}2013-04-14 15:46:15.061 OAuthDemo[350:c07] access token is:2.00QF7O9Cn7SuKDdeaf7e6529rPILeC

Next we will explain this Code:

1. First, we accept the URL after authorization redirection in the (bool) webview :( uiwebview *) webview shouldstartloadwithrequest :( nsurlrequest *) Request navigationtype :( uiwebviewnavigationtype) navigationtype function.

2. However, this function may be redirected multiple times during the authorization process. What we need is the Redirection URL containing the Code parameter. Therefore, we need to find this URL, we are looking at whether the URL after his redirection contains @ "http://www.baidu.com /? "This prefix contains the returned data (CODE) in the URL containing this prefix ).

3. Then, extract the code parameter value from the URL. The method is as follows: first determine the range of "code =", and then determine the range of the value of the Code parameter, so that the value of the Code is found.

typedef struct _NSRange {      NSUInteger location;      NSUInteger length;} NSRange;DescriptionA structure used to describe a portion of a series—such as characters in a string or objects in an NSArray object.

4. The value of the Code parameter is found, and the next step is to call the access token API, which uses synchronous POST requests.

5. The last step is to separate the access_token parameter from the data returned by the access token API call.

Note the parameters returned by this API.

{       "access_token": "ACCESS_TOKEN",       "expires_in": 1234,       "remind_in":"798114",       "uid":"12341234" }

The data received here is placed in the string, which is obviously of the JSON type. The processing here adopts the third-party class library jsonkit, so we need to import this class library, during use, you may encounter an Arc problem, that is, to add the arc feature to this third-party class library in the ARC project.

The method used here is

-(ID) objectfromjsonstring; put the data in the dictionary to facilitate the separation of access_token.

Complete. You can understand the program running result.

Related Article

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.