IOS Sina Weibo client demo practices (2) Authorization page

Source: Internet
Author: User

The previous blog post-Sina Weibo client demo (I) oauth2.0 certification has talked about how to obtain the access_token. Now, we need to do the UI part of the authorization interface.

The authorization page is a webview, which can be loaded to the authorization interface according to the URL. The following is the authorization API: https://api.weibo.com/oauth2/authorize. the URL of the authorization interface is as follows:

+ (NSString *) returnOAuthUrlString {    return [NSString stringWithFormat:@"%@?client_id=%@&redirect_uri=%@&response_type=code&display=mobile&state=authorize",OAuth_URL,APP_KEY,APP_REDIRECT_URL];}

The following describes how to deal with this view.

(1) first, store the acess_token and use nsuserdefaults for data persistence. The advantage is that if the authorization interface appears for the first login, the authorization interface is saved after authorization, and the authorization interface is not displayed after logon, go to the Weibo homepage.

The related code for processing is as follows (in this process, I also added a method: Obtain the user's uid, which is also frequently used in subsequent API calls, UID is also saved to nsuserdefaults ):

-(Void) getaccesstoken: (nsstring *) code {// string nsmutablestring * accesstokenurlstring = [[nsmutablestring alloc] initwithformat: @ "% @? Client_id =%@ & region =%@ & grant_type = authorization_code & redirect_uri =%@ & code = ", access_token_url, app_key, app_secret, app_redirect_url]; [Your appendstring: Code]; // synchronous POST request nsurl * urlstring = [nsurl urlwithstring: accesstokenurlstring]; // Step 2: Create a request token * request = [[nsmutableurlrequest alloc] initwithurl: urlstring cachepolicy: Invalid timeouti Nterval: 10]; [Request sethttpmethod: @ "Post"]; // set the request method to post. The default value is get // step 3, connection server nsdata * received = [nsurlconnection sendsynchronousrequest: Request returningresponse: Nil error: Nil]; nsstring * backstring = [[nsstring alloc] initwithdata: received encoding: enabled]; // how to obtain access_token nsdictionary * dictionary = [backstring objectfromjsonstring] From backstring; [[nsuserdefaults standarduserdefa Ults] setobject: [dictionary objectforkey: @ "access_token"] forkey: @ "access_token"]; [[nsuserdefaults standarduserdefaults] synchronize]; // obtain the UID [self getuidstring];}-(void) getuidstring {nsstring * uidurlstring = [[nsstring alloc] initwithformat: @ "% @? Access_token = % @ ", get_uid_url, [infoforsina Response]; nsurlrequest * request = [[nsurlrequest alloc] initwithurl: [nsurl urlwithstring: uidurlstring]; nserror * Error; nsdata * uiddata = [nsurlconnection sendsynchronousrequest: Request returningresponse: Nil error: & error]; nsstring * uidstring = [[nsstring alloc] initwithdata: uiddata encoding: encoding]; nsdictionary * uiddictionary = [uidstring objectfromjsonstring]; [[nsuserdefaults standarduserdefaults] setobject: [uiddictionary objectforkey: @ "uid"] forkey: @ "uid"]; [[nsuserdefaults standarduserdefaults] synchronize];}

Here is a brief introduction to nsuserdefaults:


The nsuserdefaults class provides convenience methods for accessing common types such as floats, doubles, integers, booleans, and URLs. A default object must be a property list, that is, an instance of (or for collections
A combination of instances of): nsdata, nsstring, nsnumber, nsdate, nsarray, or nsdictionary. if you want to store any other type of object, you should typically archive it to create an instance of nsdata.
Nsuserdefaults is the easiest way to store data locally. nsuserdefaults is used to store data with a small amount of data, such as user configuration. Not all things can be put in, only nsstring, nsnumber, nsdate, nsarray, and nsdictionary are supported. If you want to store some custom (except as mentioned above) data, you should convert it to nsdata
(Some people may think of saving my custom data to nsarray. Isn't that enough? The answer is no !)

The synchronize method, which is automatically invoked at periodic intervals, keeps the in-memory cache in sync with a user's ults database.

Call the synchronization method synchronize regularly to maintain data and synchronize data.

Values returned from nsuserdefaults are immutable, even if you set a mutable object as the value.

The returned value from nsuserdefaults cannot be changed, even if you set a variable object as the value.

Persistence of nsurl and file reference URLs

Of course, nsurl and URLs can also be persistently maintained.

You can find the getter and setter methods in the document to set them. I will not talk about it here.

The following describes in detail how to read and write custom data in nsuserdefaults (generally some custom classes ).

Solution: encode a custom class object into nsdata for storage and decode it when used. Two methods in the <nscoding> protocol must be implemented in the Custom class:-(ID) initwithcoder: (nscoder *) coder (encoding) and-(void) encodewithcoder :( nscoder
*) ACO (Decoding ).

The following is a small demo program. I have defined a student class, which has two properties: chinaesenamestring and englishnamestring. The encoding and decoding methods are implemented in the implementation method. (Add the nscoding protocol ).

The following are the. h and. M file codes, which are very simple.

#import <Foundation/Foundation.h>@interface Student : NSObject <NSCoding>@property (nonatomic, strong) NSString *chinaeseNameString;@property (nonatomic, strong) NSString *englishNameString;@end

#import "Student.h"@implementation Student@synthesize chinaeseNameString = _chinaeseNameString;@synthesize englishNameString = _englishNameString;- (void) encodeWithCoder:(NSCoder *)aCoder {    [aCoder encodeObject:_chinaeseNameString forKey:@"chinaeseNameString"];    [aCoder encodeObject:_englishNameString forKey:@"englishNameString"];}- (id) initWithCoder: (NSCoder *)coder {    if (self = [super init])    {        _chinaeseNameString = [coder decodeObjectForKey:@"chinaeseNameString"];        _englishNameString = [coder decodeObjectForKey:@"englishNameString"];    }    return self;}@end


The following code creates a student instance, encodes it into nsdata, stores it in nsuserdefaults, extracts and decodes it for display.

Student * Stu = [[STUDENT alloc] init]; Stu. chinaesenamestring = @ "Xiao Deng"; Stu. englishnamestring = @ "xiaodeng"; nsdata * Data = [[nsdata alloc] init]; Data = [nskeyedarchiver failed: Stu]; [[nsuserdefaults standarduserdefaults] setobject: Data forkey: @ "student"]; [[nsuserdefaults standarduserdefaults] synchronize]; Student * anotherstu = [[STUDENT alloc] init]; nsdata * anotherdata = [[nsdata alloc] init]; anotherdata = [[nsuserdefaults standarduserdefaults] objectforkey: @ "student"]; anotherstu = [unknown: anotherdata]; nslog (@ "anotherstu chinaesename: % @", anotherstu. chinaesenamestring); nslog (@ "anotherstu englishname: % @", anotherstu. englishnamestring );


Note two methods:

+ (ID) unarchiveobjectwithdata :( nsdata *) data
Decodes and returns the object graph previusly encoded by nskeyedarchiver and stored in a given nsdata object. It is the nskeyedarchiver Class Method

+ (ID) unarchiveobjectwithdata :( nsdata *) data
Decodes and returns the object graph previusly encoded by nskeyedarchiver and stored in a given nsdata object. It is the nskeyedunarchiver Class Method

(2) At the beginning of the program running, I set a welcome interface view imageview to display an image of Sina Weibo, with an animation jump delay of 0.8 seconds. Determine which view to jump to based on whether access_token is saved in nsuserdefaults (authorization view webview or Weibo homepage view mainview ).

The code is implemented as follows:

-(Void) viewdidload {[Super viewdidload]; // do any additional setup after loading the view. HUD = [[mbprogresshud alloc] init]; If ([[nsuserdefaults standarduserdefaults] objectforkey: @ "access_token"] = nil) {Hud. labeltext = @ "loading authorization page... "; [HUD show: Yes]; [self. view addsubview: HUD]; nsstring * oauthurlstring = [infoforsina Response]; nsurlrequest * request = [[nsurlrequest alloc] initwithurl: [nsurl urlwithstring: oauthurlstring]; [self. webview setdelegate: Self]; [self. webview loadrequest: request]; _ imageview. hidden = no; timer = [nstimer scheduledtimerwithtimeinterval: 0.8 target: Self selector: @ selector (gowebview) userinfo: Nil repeats: No];} else {Hud. labeltext = @ "loading Weibo content... "; [HUD show: Yes]; [self. view addsubview: HUD]; _ imageview. hidden = no; timer = [nstimer scheduledtimerwithtimeinterval: 0.8 target: Self selector: @ selector (gomainview) userinfo: Nil repeats: No] ;}}-(void) gowebview {[uiview beginanimations: Nil context: NULL]; [uiview setanimationduration: 0.8]; [uiview setanimationtransition: uiviewanimationtransitionflipfromright forview: Self. view cache: Yes]; _ imageview. hidden = yes; [uiview commitanimations];}-(void) gomainview {[uiview beginanimations: Nil context: NULL]; [uiview setanimationduration: 0.8]; [uiview progress: Previous forview: self. view cache: Yes]; _ imageview. hidden = yes; [uiview commitanimations]; [HUD removefromsuperview]; [self defined: @ "mainsegue" Sender: Nil];}-(void) webviewdidfinishload :( uiwebview *) webview {[HUD removefromsuperview];}

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.