微博閱讀器demo(一)OAuth 2.0 認證

        微博閱讀器demo實現過程分爲兩個部分:

        第一部分爲通過OAuth 2.0 認證

首先註冊一個微博開放平臺的開發者賬號,創建一個應用,獲得app key和app secret。前往管理中心-》應用信息-》高級信息,編輯OAuth2.0 授權設置,將其設置爲一個網址。

查看微博OAuth2API,可知微博OAuth 2.0認證分爲兩步:1.請求授權;2.獲取授權。

        請求授權:用Get方法調用接口“https://api.weibo.com/oauth2/authorize”,加上請求參數。調用uiwebview 的 loadRequest顯示授權頁面

- (void)viewDidLoad
{
    self.httpHelper =[[HttpHelper alloc]init];
    self.urlHelper = [[UrlHelper alloc]init];
    [super viewDidLoad];
    NSString * redirect_uri =[self.urlHelper  urlForKey:@"redirect_uri"];
    NSString * url = [NSString stringWithFormat:[self.urlHelper urlForKey:@"authorize"],APP_KEY,redirect_uri];
    NSURLRequest * request = [[NSURLRequest alloc]initWithURL:[NSURL URLWithString:url]];
    [self.webView setDelegate:self];
    [self.webView loadRequest:request];
}
我將demo所用到的所有接口存放在一個plist文件中,並創建一個輔助類UrlHelper進行管理,上面的urlHelper即UrlHelper的一個實例,UrlHelper代碼如下:

#import <Foundation/Foundation.h>


@interface UrlHelper : NSObject
@property (nonatomic) NSDictionary * urlDictionary;   //用於保存plist文件中的數據
-(NSString *) urlForKey:(NSString *)key;              //通過鍵值找到對應數據
-(NSString *) accessToken;
@end




#import "UrlHelper.h"


@implementation UrlHelper
-(id) init
{
    self = [super init];
	if(self != nil)
	{
		self.urlDictionary = [[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Url" ofType:@"plist"]];
	}
	return self;
}


-(NSString *) urlForKey:(NSString *)key
{
    NSString * url = nil;
    url = [self.urlDictionary objectForKey:key];
    return url;
}


-(NSString *) accessToken
{
    NSUserDefaults * userDefault = [NSUserDefaults standardUserDefaults];
    NSString * token = [userDefault objectForKey:@"access_token"];
    return token;
}
@end

plist中的數據類似如下:https://api.weibo.com/oauth2/authorize?client_id=%@&amp;redirect_uri=%@&amp;display=moblie&amp;response_type=code&amp;state=authorize

只需傳入client_id(即app key)和回調地址,即可得到完整授權地址。請求成功,UIWebview會重定向到回調地址所指定的網址,重定向的url中就包含了我們需要的code,我們只需實現 UIWebViewDelegate 的委託方法   -(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType      判斷當前url是否以我們指定的回調地址,如果是就截取出code,並進行下一步的“獲取授權”

-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    NSString * str =[[request URL] absoluteString];       //   獲取完整路徑
    if([str hasPrefix:[self.urlHelper urlForKey:@"redirect_uri"]])      //是否以回調地址開頭
    {
        NSArray * array = [str componentsSeparatedByString:@"code="];      //  獲取code
        NSString * code = [array lastObject];
        if(code)      
        {
            NSString * paramterString  =[NSString stringWithFormat:[self.urlHelper urlForKey:@"access_token_paramter"],APP_KEY,APP_SECRECT,[self.urlHelper urlForKey:@"redirect_uri"],code];   //  獲取post方法的請求body
   
            NSData * receive = [self.httpHelper SynchronousPostWithUrl:[self.urlHelper urlForKey:@"access_token"] andParameter:paramterString];   //  這裏用post方法(只能用post方法)進行獲取授權,其中httpHelper爲自定義的類

            NSDictionary * dic =[NSJSONSerialization JSONObjectWithData:receive options:NSJSONReadingMutableLeaves error:nil];     //利用NSJSONSerialization 將json文件解析成字典
            NSUserDefaults * userDefault = [NSUserDefaults standardUserDefaults];       //  數據持久化
            [userDefault setObject:[dic objectForKey:@"access_token"] forKey:@"access_token"];     //   保存access_token
            [userDefault setObject:[dic objectForKey:@"expires_in"] forKey:@"expires_in"];
            [userDefault setObject:[dic objectForKey:@"uid"] forKey:@"uid"];         
            [userDefault synchronize];
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];    //  獲取access_token成功,跳轉到主界面
            [self presentModalViewController:[storyboard instantiateInitialViewController] animated:YES ];
        }
    }
    return YES;
}

另外有一點要注意的是,如果應用未經過審覈,進行授權的微博賬戶必須是開發者賬號的微博賬戶或測試賬戶(在應用管理中添加)。

至此,我們就拿到了access_token,並將其存在文件中,OAuth2.0請求成功。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章