版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/winer888/article/details/51114656
前言:
平时 在开发一个app应用时,往往 为了考虑用户体验以及防治用户的流失,都需要给应用添加第三方授权登录的功能。下面给大家说一下两种实现授权登录以及请求微博openAPI的方法。第一种方法:使用WeiboSDK授权实现
(注:应先参照官方SDK文档,按要求导入相应的framework文件,然后在代码中声明<WBHttpRequestDelegate,WeiboSDKDelegate>代理)
①定义应⽤认证所需的几个常量:
AppKey:第三⽅方应⽤用申请的appkey,⽤用来⾝身份鉴证、显⽰示来源等;
AppRedirectURL:应⽤用回调⻚页,在进⾏行Oauth2.0登录认证时所⽤用。
- #define kAppKey @"2066759248"
- #define kRedirectURL @"https://api.weibo.com/oauth2/default.html"
②注册appkey(clientid) :程序启动时,在代码中向微博终端注册你的 Appkey
- - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
- [WeiboSDK enableDebugMode:YES];
- [WeiboSDK registerApp:kAppKey];
- return YES;
- }
③重写AppDelegate的handleOpenURL和openURL⽅方法 :
- -(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
- {
- return [WeiboSDK handleOpenURL:url delegate:self];
- }
- -(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
- {
- return [WeiboSDK handleOpenURL:url delegate:self];
- }
④你的授权登录按钮的@selector响应事件应为以下内容:
- { //微博客户端授权认证
- WBAuthorizeRequest *request=[WBAuthorizeRequest request];
- request.redirectURI=@"https://api.weibo.com/oauth2/default.html" ;
- request.scope = @"all";
- [WeiboSDK sendRequest:request];
- }
⑤用这事件能收到授权成功的回应,并根据回应可以得到基本的数据
(在iOS9下直接进行HTTP请求.系统会告诉我们不能直接使用HTTP进行请求,需要在Info.plist新增一段用于控制ATS的配置: 配置方法)
- -(void)didReceiveWeiboResponse:(WBBaseResponse *)response
- {
- if ([response isKindOfClass:WBAuthorizeResponse.class])
- { //获取accessToken,userID等,wbtoken,wbcurrentUserID,wbRefreshToken是自定义NSString型的属性
- self.wbtoken = [(WBAuthorizeResponse *)response accessToken];
- self.wbCurrentUserID = [(WBAuthorizeResponse *)response userID];
- self.wbRefreshToken = [(WBAuthorizeResponse *)response refreshToken];
- //获取用户的粉丝数、关注数、微博数,根据微博开放平台获取此数据必须需要access_token,uids
- NSArray *arr=[NSArray arrayWithObjects:self.wbtoken,self.wbCurrentUserID,nil];
- NSArray *arr1=[NSArray arrayWithObjects:@"access_token",@"uids", nil];
- NSDictionary *dic=[[NSDictionary alloc]initWithObjects:arr forKeys:arr1];
- //发送请求 获取各种数据 对应的URL和请求方式heepMethod是不同的 详细的参考微博开放平台
- [WBHttpRequest requestWithURL:@"https://api.weibo.com/2/users/counts.json" httpMethod:@"GET" params:dic delegate:self withTag:@"me"];
- } }
⑥上面使用WBHttpRequest发送请求后,用这事件接收请求回来的数据
- -(void)request:(WBHttpRequest *)request didFinishLoadingWithResult:(NSString *)result
- {
- NSData *data=[result dataUsingEncoding:NSUTF8StringEncoding];
- NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]; //打印接收到的数据,可以根据需要而从字典里取出来
- NSLog(@"%@",dic);
- }
第二种方法:使用<UIWebViewDelegate>网页授权实现
- #import <UIKit/UIKit.h>
- //先定义一个全局变量UIWebView,并声明UIWebViewDelegate代理:
- @interface OAuthWebViewController : UIViewController<UIWebViewDelegate>
- {
- UIWebView *webView;
- }
- @end
- #import "OAuthWebViewController.h"
- @implementation OAuthWebViewController
- -(void)viewWillAppear:(BOOL)animated
- {
- [super viewWillAppear:animated];
- NSString *url=@"https://api.weibo.com/oauth2/authorize?client_id=2066759248&response_type=code&redirect_uri=https://api.weibo.com/oauth2/default.html";
- // client_id、redirect_uri后面的分别是App Key和回调页面,每个人的都是不同的,具体去微博开放平台查看
- NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
- [webView setDelegate:self];
- [webView loadRequest:request];
- }
- -(void)viewDidLoad
- {
- [super viewDidLoad];
- }
- #pragma mark - UIWebView Delegate Methods
- -(void)webViewDidFinishLoad:(UIWebView *)_webView
- {
- NSString *url = _webView.request.URL.absoluteString;
- NSLog(@"absoluteString:%@",url);
- if ([url hasPrefix:@"https://api.weibo.com/oauth2/default.html?"]) {
- //找到”code=“的range
- NSRange rangeOne;
- rangeOne=[url rangeOfString:@"code="];
- //根据他“code=”的range确定code参数的值的range
- NSRange range = NSMakeRange(rangeOne.length+rangeOne.location, url.length-(rangeOne.length+rangeOne.location));
- //获取code值
- NSString *codeString = [url substringWithRange:range];
- NSLog(@"code = :%@",codeString);
- //access token调用URL的string
- 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="];
- // client_id、client_secret、redirect_uri后面的分别是App Key、App Secret、回调页面
- [muString appendString:codeString];
- NSLog(@"access token url :%@",muString);
- //第一步,创建URL
- NSURL *urlstring = [NSURL URLWithString:muString];
- //第二步,创建请求
- NSMutableURLRequest *request = [[NSMutableURLRequest alloc]initWithURL:urlstring cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
- [request setHTTPMethod:@"POST"];//设置请求方式为POST,默认为GET
- NSString *str = @"type=focus-c";//设置参数
- NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
- [request setHTTPBody:data];
- //第三步,连接服务器
- NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
- NSError *error;
- //如何从str1中获取到access_token、uid
- NSDictionary *dictionary = [NSJSONSerialization JSONObjectWithData:received options:NSJSONReadingMutableContainers error:&error];
- NSString *_access_token = [dictionary objectForKey:@"access_token"];
- NSString *uid=[dictionary objectForKey:@"uid"];
- //如果获取到access_token,则授权成功,接下来是获取微博用户数据,与上面类似
- if(_access_token)
- {
- //根据微博开放平台的要求,填写相应数据
- NSString *str2=[NSString stringWithFormat:@"https://api.weibo.com/2/users/show.json?access_token=%@&uid=%@",_access_token,uid];
- NSURL *url2 = [NSURL URLWithString:str];
- NSMutableURLRequest *request2= [[NSMutableURLRequest alloc]initWithURL:url2 cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
- [request2 setHTTPMethod:@"POST"];
- NSData *received2= [NSURLConnection sendSynchronousRequest:request2 returningResponse:nil error:nil];
- NSDictionary *dictionary2 = [NSJSONSerialization JSONObjectWithData:received2 options:NSJSONReadingMutableContainers error:&error];
- //输出接收到的字典,根据需要取相应的值
- NSLog(@"%@",dictionary);
- }
- }
- }
- @end