iOS微博授权登录及获取用户数据的方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/winer888/article/details/51114656

前言:

           平时 在开发一个app应用时,往往 为了考虑用户体验以及防治用户的流失,都需要给应用添加第三方授权登录的功能。下面给大家说一下两种实现授权登录以及请求微博openAPI的方法。


第一种方法:使用WeiboSDK授权实现

(注:应先参照官方SDK文档,按要求导入相应的framework文件,然后在代码中声明<WBHttpRequestDelegate,WeiboSDKDelegate>代理)

定义应⽤认证所需的几个常量:

AppKey:第三⽅方应⽤用申请的appkey,⽤用来⾝身份鉴证、显⽰示来源等;

AppRedirectURL:应⽤用回调⻚页,在进⾏行Oauth2.0登录认证时所⽤用。

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. #define kAppKey @"2066759248"  
  2. #define kRedirectURL @"https://api.weibo.com/oauth2/default.html"  


注册appkey(clientid) :程序启动时,在代码中向微博终端注册你的 Appkey 

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {  
  2.     [WeiboSDK enableDebugMode:YES];  
  3.     [WeiboSDK registerApp:kAppKey];  
  4.     return YES;  
  5. }  


重写AppDelegatehandleOpenURLopenURL⽅方法 :

[objc]  view plain  copy
  1. -(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation  
  2. {  
  3.     return [WeiboSDK handleOpenURL:url delegate:self];  
  4. }  
  5. -(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url  
  6. {  
  7.     return [WeiboSDK handleOpenURL:url delegate:self];  
  8. }  


你的授权登录按钮的@selector响应事件应为以下内容:

[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. {                                                                                                                            //微博客户端授权认证                             
  2.     WBAuthorizeRequest *request=[WBAuthorizeRequest request];  
  3.     request.redirectURI=@"https://api.weibo.com/oauth2/default.html" ;  
  4.     request.scope = @"all";  
  5.     [WeiboSDK sendRequest:request];  
  6. }  

用这事件能收到授权成功的回应,并根据回应可以得到基本的数据
(在iOS9下直接进行HTTP请求.系统会告诉我们不能直接使用HTTP进行请求,需要在Info.plist新增一段用于控制ATS的配置: 配置方法)
[objc]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. -(void)didReceiveWeiboResponse:(WBBaseResponse *)response  
  2. {  
  3.      if ([response isKindOfClass:WBAuthorizeResponse.class])  
  4.     {    //获取accessToken,userID等,wbtoken,wbcurrentUserID,wbRefreshToken是自定义NSString型的属性  
  5.         self.wbtoken = [(WBAuthorizeResponse *)response accessToken];  
  6.         self.wbCurrentUserID = [(WBAuthorizeResponse *)response userID];  
  7.         self.wbRefreshToken = [(WBAuthorizeResponse *)response refreshToken];  
  8.                                                          
  9. //获取用户的粉丝数、关注数、微博数,根据微博开放平台获取此数据必须需要access_token,uids   
  10.         NSArray *arr=[NSArray arrayWithObjects:self.wbtoken,self.wbCurrentUserID,nil];  
  11.         NSArray *arr1=[NSArray arrayWithObjects:@"access_token",@"uids", nil];  
  12.         NSDictionary *dic=[[NSDictionary alloc]initWithObjects:arr forKeys:arr1];  
  13. //发送请求 获取各种数据 对应的URL和请求方式heepMethod是不同的 详细的参考微博开放平台   
  14.  [WBHttpRequest requestWithURL:@"https://api.weibo.com/2/users/counts.json" httpMethod:@"GET" params:dic delegate:self withTag:@"me"];  
  15. }  }

 
        
上面使用WBHttpRequest发送请求后,用这事件接收请求回来的数据
[objc]  view plain  copy
  1. -(void)request:(WBHttpRequest *)request didFinishLoadingWithResult:(NSString *)result  
  2. {  
  3.     NSData *data=[result dataUsingEncoding:NSUTF8StringEncoding];  
  4.     NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];                //打印接收到的数据,可以根据需要而从字典里取出来  
  5.    NSLog(@"%@",dic);  
  6. }  



第二种方法:使用<UIWebViewDelegate>网页授权实现

[objc]  view plain  copy
  1. #import <UIKit/UIKit.h>   
  2. //先定义一个全局变量UIWebView,并声明UIWebViewDelegate代理:  
  3. @interface OAuthWebViewController : UIViewController<UIWebViewDelegate>   
  4. {  
  5. UIWebView *webView;  
  6. }   
  7. @end   



[objc]  view plain  copy
  1. #import "OAuthWebViewController.h"  
  2.   
  3. @implementation OAuthWebViewController  
  4.   
  5. -(void)viewWillAppear:(BOOL)animated  
  6. {  
  7.     [super viewWillAppear:animated];  
  8.       
  9.     NSString *url=@"https://api.weibo.com/oauth2/authorize?client_id=2066759248&response_type=code&redirect_uri=https://api.weibo.com/oauth2/default.html";  
  10.     // client_id、redirect_uri后面的分别是App Key和回调页面,每个人的都是不同的,具体去微博开放平台查看  
  11.     NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:url]];  
  12.     [webView setDelegate:self];  
  13.     [webView loadRequest:request];  
  14. }  
  15.   
  16. -(void)viewDidLoad  
  17. {  
  18.     [super viewDidLoad];  
  19. }  
  20.   
  21. #pragma mark - UIWebView Delegate Methods  
  22.   
  23. -(void)webViewDidFinishLoad:(UIWebView *)_webView  
  24. {  
  25.     NSString *url = _webView.request.URL.absoluteString;  
  26.     NSLog(@"absoluteString:%@",url);  
  27.       
  28.     if ([url hasPrefix:@"https://api.weibo.com/oauth2/default.html?"]) {  
  29.           
  30.         //找到”code=“的range  
  31.         NSRange rangeOne;  
  32.         rangeOne=[url rangeOfString:@"code="];  
  33.           
  34.         //根据他“code=”的range确定code参数的值的range  
  35.         NSRange range = NSMakeRange(rangeOne.length+rangeOne.location, url.length-(rangeOne.length+rangeOne.location));  
  36.         //获取code值  
  37.         NSString *codeString = [url substringWithRange:range];  
  38.         NSLog(@"code = :%@",codeString);  
  39.           
  40.         //access token调用URL的string  
  41.         NSMutableString *muString = [[NSMutableString alloc] initWithString:@"https://api.weibo.com/oauth2/access_token?client_id=2066759248&client_secret=fa39a851630a5d4ac05b26f7f4c7a670&grant_type=authorization_code&redirect_uri=https://api.weibo.com/oauth2/default.html&code="];  
  42.         // client_id、client_secret、redirect_uri后面的分别是App Key、App Secret、回调页面  
  43.         [muString appendString:codeString];  
  44.         NSLog(@"access token url :%@",muString);  
  45.           
  46.         //第一步,创建URL  
  47.         NSURL *urlstring = [NSURL URLWithString:muString];  
  48.         //第二步,创建请求  
  49.         NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:urlstring cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];  
  50.         [request setHTTPMethod:@"POST"];//设置请求方式为POST,默认为GET  
  51.         NSString *str = @"type=focus-c";//设置参数  
  52.         NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];  
  53.         [request setHTTPBody:data];  
  54.         //第三步,连接服务器  
  55.         NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];  
  56.           
  57.         NSError *error;  
  58.         //如何从str1中获取到access_token、uid  
  59.         NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:received options:NSJSONReadingMutableContainers error:&error];  
  60.           
  61.         NSString *_access_token = [dictionary objectForKey:@"access_token"];  
  62.         NSString *uid=[dictionary objectForKey:@"uid"];  
  63.          //如果获取到access_token,则授权成功,接下来是获取微博用户数据,与上面类似  
  64.         if(_access_token)  
  65.         {  
  66.             //根据微博开放平台的要求,填写相应数据  
  67.             NSString *str2=[NSString stringWithFormat:@"https://api.weibo.com/2/users/show.json?access_token=%@&uid=%@",_access_token,uid];  
  68.             NSURL *url2 = [NSURL URLWithString:str];  
  69.             NSMutableURLRequest *request2= [[NSMutableURLRequest alloc]initWithURL:url2 cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];  
  70.             [request2 setHTTPMethod:@"POST"];  
  71.             NSData *received2= [NSURLConnection sendSynchronousRequest:request2 returningResponse:nil error:nil];  
  72.             NSDictionary *dictionary2 = [NSJSONSerialization JSONObjectWithData:received2 options:NSJSONReadingMutableContainers error:&error];  
  73.             //输出接收到的字典,根据需要取相应的值  
  74.             NSLog(@"%@",dictionary);  
  75.         }  
  76.     
  77.     }    
  78. }    
  79.   
  80. @end  

猜你喜欢

转载自blog.csdn.net/winer888/article/details/51114656