使用OAuth2
1.获取新浪的登录界面(UIWebView)
2.登陆成功后,会从服务器获取一个状态码(code)
3.用code向服务器换取一个accessToken令牌
//登陆
- (IBAction)loginBtnDidClicked:(UIButton *)sender {
//1.使用OAuth2/authorize发起请求
NSString *urlString = [NSString stringWithFormat:@"https://api.weibo.com/oauth2/authorize?client_id=%@&redirect_uri=%@", kAppKey, kRedirect_uri];
NSURL *url = [NSURL URLWithString:urlString];
//创建请求
NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:60];
//使用UIWebView加载页面
self.webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
_webView.delegate = self;
[self.view addSubview:_webView];
[_webView loadRequest:request];
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
//目标:获取code的状态码
//解决方案:对即将加载的request对应的URL进行解析,一旦URL里面包含code=,那么就停止
if ([[request.URL relativeString] containsString:@"code="]) {
//说明此刻即将请求的request里面包含了code
NSRange range = [[request.URL relativeString] rangeOfString:@"code="];
NSString *code = [[request.URL relativeString] substringFromIndex:range.location + range.length];
//关闭webView
[_webView removeFromSuperview];
//使用这个code去换取一个accessToken令牌
//解决方案,向服务器发送一个POST请求
NSURL *codeURL = [NSURL URLWithString:@"https://api.weibo.com/oauth2/access_token"];
//创建一个可变请求(因为要修改头部信息)
NSMutableURLRequest *codeResquest = [NSMutableURLRequest requestWithURL:codeURL];
//设置请求方式为POST
[codeResquest setHTTPMethod:@"POST"];
//准备上传的数据
NSString *dataString = [NSString stringWithFormat:@"client_id=%@&client_secret=%@&grant_type=authorization_code&code=%@&redirect_uri=%@", kAppKey, kAppSecret, code, kRedirect_uri];
NSData *upData = [dataString dataUsingEncoding:NSUTF8StringEncoding];
//创建session
NSURLSession *session = [NSURLSession sharedSession];;
NSURLSessionUploadTask *uploadTask = [session uploadTaskWithRequest:codeResquest fromData:upData completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
//NSData -> NSDictionary
NSDictionary *resultDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:&error];
//保存access_token expires_in uid
NSString *accessToken = [resultDic objectForKey:@"access_token"];
NSString *expiresIn = [resultDic objectForKey:@"expires_in"];
NSString *uid = [resultDic objectForKey:@"uid"];
NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
[userDefaults setObject:accessToken forKey:kAccessTokenKey];
[userDefaults setObject:expiresIn forKey:kExpiresTimeKey];
[userDefaults setObject:uid forKey:kUserIDKey];
[userDefaults synchronize];
}];
[uploadTask resume];
return NO;
} else{
return YES;
}
}
网友评论