oAuth授权:
新浪微博开放平台网址:http://open.weibo.com
#import "OAuthViewController.h"
#import "AFNetworking.h"
#import "NetWorkTask.h"
#import "JSONKit.h"
#import "MJExtension.h"
#import "OAuthModels.h"
#import "AppDelegate.h"
@interface OAuthViewController ()<UIWebViewDelegate>
@end
@implementation OAuthViewController
- (void)viewDidLoad {
[super viewDidLoad];
// 1.创建一个webView
UIWebView *webView = [[UIWebView alloc] init];
webView.frame = self.view.bounds;
[self.view addSubview:webView];
webView.delegate = self;
// 2.用webView加载登录页面(新浪提供的)
// 请求地址:https://api.weibo.com/oauth2/authorize
/* 请求参数:
client_id true string 申请应用时分配的AppKey。
redirect_uri true string 授权回调地址,站外应用需与设置的回调地址一致,站内应用需填写canvas page的地址。
*/
NSURL *url = [NSURL URLWithString:@"https://api.weibo.com/oauth2/authorize?client_id=836890350&redirect_uri=http://baidu.com"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
// 1.获得url
NSString *url = request.URL.absoluteString;
NSLog(@"%@",url);
// 2.判断是否为回调地址
NSRange rang = [url rangeOfString:@"code="];
if(rang.length !=0){// 是回调地址
NSLog(@"rang.location=%lu,rang.length=%lu",(unsigned long)rang.location,(unsigned long)rang.length);
// 截取code=后面的参数值
NSInteger index = rang.location+rang.length;
NSString *code = [url substringFromIndex:index];
NSLog(@"code = %@",code);
// 利用code换取一个accessToken
[self accessTokenWithCode:code];
// 禁止加载回调地址
return NO;
}
return YES;
}
-(void)accessTokenWithCode:(NSString *)code{
/*
URL:https://api.weibo.com/oauth2/access_token
请求参数:
client_id:申请应用时分配的AppKey
client_secret:申请应用时分配的AppSecret
grant_type:使用authorization_code
redirect_uri:授权成功后的回调地址
code:授权成功后返回的code
*/
// 1.请求管理者
NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
[dict setObject:@"836890350" forKey:@"client_id"];
[dict setObject:@"e151e5cf10c235cd854e5cdf274dbe61" forKey:@"client_secret"];
[dict setObject:@"authorization_code" forKey:@"grant_type"];
[dict setObject:@"http://baidu.com" forKey:@"redirect_uri"];
[dict setObject:code forKey:@"code"];
// 3.发送请求
[NetWorkTask postWithMethod:@"https://api.weibo.com/oauth2/access_token" forParamDic:dict forHttpHeader:nil succ:^(NSDictionary *successDict, id responseObject) {
NSLog(@"网络请求成功: responseObject:%@",successDict);
//沙盒路径:
NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
NSLog(@"doc=%@",doc);
NSString *path = [doc stringByAppendingPathComponent:@"account.plist"];
OAuthModels *oAuth = [OAuthModels mj_objectWithKeyValues:successDict];
NSLog(@"%@",oAuth.remind_in);
//通过归档的方式存储
[NSKeyedArchiver archiveRootObject:oAuth toFile:path];
//切换根控制器
AppDelegate *app = [UIApplication sharedApplication].delegate;
[app switchRootViewController];
} failure:^(NSDictionary *failDict, NSError *error) {
NSLog(@"网络请求失败11");
}];
}
/*
//网络发送请求的三种不同写法,返回结果相同
-(void)demo{
//第一种,NetWorkTask,封闭后的AFHTTPSessionManager请求
[NetWorkTask postWithMethod:@"https://api.weibo.com/oauth2/access_token" forParamDic:dict forHttpHeader:nil succ:^(NSDictionary *successDict, id responseObject) {
NSLog(@"网络请求成功: responseObject:%@",successDict);
} failure:^(NSDictionary *failDict, NSError *error) {
NSLog(@"网络请求失败11");
}];
//第二种,AFHTTPSessionManager请求
AFHTTPSessionManager *manager=[[AFHTTPSessionManager alloc]init];
manager.requestSerializer = [AFHTTPRequestSerializer serializer];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
[manager POST:@"https://api.weibo.com/oauth2/access_token" parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) {
NSLog(@"网络请求成功: responseObject:%@",responseObject);
//JOSN转换->字典数据
if (responseObject != nil) {
NSData *responseData = responseObject;
NSString *returnJsonString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSDictionary *dic = [returnJsonString objectFromJSONString];
NSLog(@"%@",dic);
}
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
NSLog(@"网络请求失败11");
}];
// 第三种,AFHTTPRequestOperationManager旧方法
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
[mgr POST:@"https://api.weibo.com/oauth2/access_token" parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary *responseObject) {
NSLog(@"网络请求成功: responseObject:%@",responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSLog(@"请求失败-%@", error);
}];
}*/
@interface OAuthModels : NSObject
/** string 用于调用access_token,接口获取授权后的access token。*/
@property (nonatomic, copy) NSString *access_token;
/** string access_token的生命周期,单位是秒数。*/
@property (nonatomic, copy) NSNumber *expires_in;
@property (nonatomic, copy) NSNumber *remind_in;
/** string 当前授权用户的UID。*/
@property (nonatomic, copy) NSString *uid;
/** access token的创建时间 */
@property (nonatomic, strong) NSDate *created_time;
/** 用户的昵称 */
@property (nonatomic, copy) NSString *name;
//+ (instancetype)accountWithDict:(NSDictionary *)dict; //原始方法
@end
#import "OAuthModels.h"
#import "MJExtension.h"//第三方库
@implementation OAuthModels
MJCodingImplementation //归档与解归档
//原始方法如下
//+ (instancetype)accountWithDict:(NSDictionary *)dict
//{
// HWAccount *account = [[self alloc] init];
// account.access_token = dict[@"access_token"];
// account.uid = dict[@"uid"];
// account.expires_in = dict[@"expires_in"];
// // 获得账号存储的时间(accessToken的产生时间)
// account.created_time = [NSDate date];
// return account;
//}
//MJCodingImplementation
/**
* 当一个对象要归档进沙盒中时,就会调用这个方法
* 目的:在这个方法中说明这个对象的哪些属性要存进沙盒
*/
//- (void)encodeWithCoder:(NSCoder *)encoder
//{
// [encoder encodeObject:self.access_token forKey:@"access_token"];
// [encoder encodeObject:self.expires_in forKey:@"expires_in"];
// [encoder encodeObject:self.uid forKey:@"uid"];
// [encoder encodeObject:self.created_time forKey:@"created_time"];
// [encoder encodeObject:self.name forKey:@"name"];
//}
/**
* 当从沙盒中解档一个对象时(从沙盒中加载一个对象时),就会调用这个方法
* 目的:在这个方法中说明沙盒中的属性该怎么解析(需要取出哪些属性)
*/
//- (id)initWithCoder:(NSCoder *)decoder
//{
// if (self = [super init]) {
// self.access_token = [decoder decodeObjectForKey:@"access_token"];
// self.expires_in = [decoder decodeObjectForKey:@"expires_in"];
// self.uid = [decoder decodeObjectForKey:@"uid"];
// self.created_time = [decoder decodeObjectForKey:@"created_time"];
// self.name = [decoder decodeObjectForKey:@"name"];
// }
// return self;
//}
@end
@implementation AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Override point for customization after application launch.
self.window.backgroundColor = [UIColor whiteColor];
// 1.创建窗口
self.window = [[UIWindow alloc] init];
self.window.frame = [UIScreen mainScreen].bounds;
// 2.设置根控制器
//解归档
//获取路径
NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
NSLog(@"path %@",path);
//拼接文件名
NSString *filePath = [path stringByAppendingPathComponent:@"account.plist"];
//读取数据
OAuthModels *oAuth = [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
if (oAuth) { // 之前已经登录成功过
[self switchRootViewController];
} else {
self.window.rootViewController = [[OAuthViewController alloc] init];
}
// 3.显示窗口
[self.window makeKeyAndVisible];
return YES;
}
//判断版本号是否一致
-(void)switchRootViewController{
//设置根控制器
NSString *key = @"CFBundleVersion";
//上一次版本号(从沙盒中取)
NSString *lastVesion = [[NSUserDefaults standardUserDefaults] objectForKey:key];
//当前软件的版本号(从Info.plist文件中获取)
NSDictionary *info = [NSBundle mainBundle].infoDictionary;
NSLog(@"%@",info);//打印Info文件内容
NSString *currentVesion = [NSBundle mainBundle].infoDictionary[key];
if ([currentVesion isEqualToString:lastVesion]) {
[self didTabBarout];
}else{
GuidePageViewController *guidePage = [[GuidePageViewController alloc]init];
self.window.rootViewController = guidePage;
//将新版本号存入沙盒
[[NSUserDefaults standardUserDefaults] setObject:currentVesion forKey:key];
[[NSUserDefaults standardUserDefaults] synchronize];
}
}