A.发送授权请求
1.使用UIWebView加载请求页面
自定义一个继承UIViewController的HVWOAuthViewController
//
// HVWOAuthViewController.m
// HVWWeibo
//
// Created by hellovoidworld on 15/2/4.
// Copyright (c) 2015年 hellovoidworld. All rights reserved.
// #import "HVWOAuthViewController.h" @interface HVWOAuthViewController () @end @implementation HVWOAuthViewController - (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view. // 创建UIWebView
UIWebView *webView = [[UIWebView alloc] init];
webView.frame = self.view.bounds; // 添加到主界面
[self.view addSubview:webView]; // 加载请求页面
NSURL *url = [NSURL URLWithString:@"https://api.weibo.com/oauth2/authorize?client_id=3942775926&redirect_uri=http://www.cnblogs.com/hellovoidworld/"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
} @end
把这个控制器作为window的根控制器运行测试:
AppDelegate:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch. // 启动后显示状态栏
UIApplication *app = [UIApplication sharedApplication];
app.statusBarHidden = NO; // 设置window
self.window = [[UIWindow alloc] init];
self.window.frame = [UIScreen mainScreen].bounds; self.window.rootViewController = [[HVWOAuthViewController alloc] init];
[self.window makeKeyAndVisible]; return YES;
}
![[iOS微博项目 - 2.2] - 在app中获取授权 [iOS微博项目 - 2.2] - 在app中获取授权](https://image.miaokee.com:8440/aHR0cHM6Ly9pbWFnZXMwLmNuYmxvZ3MuY29tL2Jsb2cvNjQ4NDczLzIwMTUwMi8wNTE2MzgxNTc2NTk4NjcucG5n.png?w=700&webp=1)
2.使用UIWebView代理拦截发送url动作,发送授权请求之后发送的url就带有access_code
/** 截取web发送请求 */
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { NSString *urlStr = request.URL.absoluteString;
NSRange range = [urlStr rangeOfString:@"http://www.cnblogs.com/hellovoidworld/?code="];
if (range.length > ) { // 如果是匹配的url,即发送的是带access_code的url
// 截取access_code
NSUInteger accessCodeLocation = range.length + range.location;
NSString *accessCode = [urlStr substringFromIndex:accessCodeLocation]; HVWLog(@"%@", accessCode); return NO; // 阻止发送,不需要跳转到重定向页面
} return YES; // 其他情况照常发送
}
Output:
5bef5308ba902cc52d9f2dc34bbfdd1c
注意这个access_code每次都不一样的
3.获取access_token
(1)获取access_token的请求API,发送POST请求
![[iOS微博项目 - 2.2] - 在app中获取授权 [iOS微博项目 - 2.2] - 在app中获取授权](https://image.miaokee.com:8440/aHR0cHM6Ly9pbWFnZXMwLmNuYmxvZ3MuY29tL2Jsb2cvNjQ4NDczLzIwMTUwMi8wNTE2MzgxNjkyMTE1NTUucG5n.png?w=700&webp=1)
(2)使用AFN框架来发送post请求
/** 根据access_code获取access_token */
- (void) accessTokenWithAccessCode:(NSString *) accessCode {
// 创建AFN的http操作请求管理者
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager]; // 参数设置
NSMutableDictionary *param = [NSMutableDictionary dictionary];
param[@"client_id"] = @"";
param[@"client_secret"] = @"cc577953b2aa3aa8ea220fd15775ea35";
param[@"grant_type"] = @"authorization_code";
param[@"code"] = accessCode;
param[@"redirect_uri"] = @"http://www.cnblogs.com/hellovoidworld/"; // 发送请求
[manager POST:@"https://api.weibo.com/oauth2/access_token" parameters:param success:^(AFHTTPRequestOperation *operation, NSDictionary *accountInfo) {
[MBProgressHUD hideHUD]; // 返回的是用户信息字典
HVWLog(@"%@", accountInfo); } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
[MBProgressHUD hideHUD]; HVWLog(@"请求access_token失败 ----> %@", error);
}]; }
(3)由于新浪返回的json数据Content-Type是 text/plain,但是AFNetworking框架默认的json序列化器不能识别,所以要修改一下json序列化器的acceptableContentType
![[iOS微博项目 - 2.2] - 在app中获取授权 [iOS微博项目 - 2.2] - 在app中获取授权](https://image.miaokee.com:8440/aHR0cHM6Ly9pbWFnZXMwLmNuYmxvZ3MuY29tL2Jsb2cvNjQ4NDczLzIwMTUwMi8wNTE2MzgxODE3MTEyNzAucG5n.png?w=700&webp=1)
- (instancetype)init {
self = [super init];
if (!self) {
return nil;
} self.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/plain", nil]; return self;
}
Output:
{
"access_token" = "2.00A5GpAGGIUpSEff44478fe90yykBw";
"expires_in" = 181897;
"remind_in" = 181897;
uid = 5508976272;
"access_token" = "2.00A5GpAGGIUpSEff44478fe90yykBw";
"expires_in" = 181897;
"remind_in" = 181897;
uid = 5508976272;
}
(4)保存返回的用户信息到沙盒
// 返回的是用户信息字典
// 存储用户信息,包括access_token到沙盒中
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *filePath = [docPath stringByAppendingPathComponent:@"accountInfo.plist"];
// 存储用户信息,包括access_token到沙盒中
NSString *docPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSString *filePath = [docPath stringByAppendingPathComponent:@"accountInfo.plist"];
[accountInfo writeToFile:filePath atomically:YES];