#pragma mark 在加载的时候创建VIEW
- (void)loadView{
_webView = [[UIWebView alloc] initWithFrame:[UIScreen mainScreen].applicationFrame];
self.view = _webView;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
//1. 加载登陆页面获取未授权 Request Token
NSString *UrlString = [KAuthorizeURL stringByAppendingFormat:@"?display=mobile&client_id=%@&redirect_uri=%@",KAppKey,KReddirectURI];
NSURL *nsurl = [NSURL URLWithString:UrlString];
NSURLRequest *rq = [NSURLRequest requestWithURL:nsurl];
[_webView loadRequest:rq];
//2. 监听页面代理监听URL
_webView.delegate = self;
}
#pragma mark webView 代理方法
#pragma mark 拦截webView
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
//1.把URL地址字符串化
NSString *Urlstring = request.URL.absoluteString;
//2.判断URL字符串中是否包含code=字符
//Range 中又location 和 length location是c开始的位置 length是到=号的长度
NSRange range = [Urlstring rangeOfString:@"code="];
if(range.length !=0 ){
//跳转到回调地址
//字符串截取
int index = range.location + range.length;
NSString *urlcode = [Urlstring substringFromIndex:index];
//用NFNetWorking
AFHTTPClient *client = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@"https://api.weibo.com"]];
NSURLRequest *post = [client requestWithMethod:@"POST" path:@"oauth2/access_token" parameters:@{
@"client_id" : KAppKey,
@"client_secret": KAppSecret,
@"grant_type" : @"authorization_code",
@"code" : urlcode,
@"redirect_uri" : KReddirectURI,
}];
// NSMutableURLRequest *post = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://api.weibo.com/oauth2/access_token"]];
// post.HTTPMethod = @"POST";
// post.HTTPBody = [[NSString stringWithFormat:@"client_id=%@&client_secret=%@&grant_type=authorization_code&code=%@&redirect_uri=%@",KAppKey,KAppSecret,urlcode,KReddirectURI] dataUsingEncoding:NSUTF8StringEncoding];
AFJSONRequestOperation *op = [AFJSONRequestOperation JSONRequestOperationWithRequest:post success:^(NSURLRequest *request, NSHTTPURLResponse *response, id JSON) {
//保存账号信息
//初始化Account 账号信息
/*
Account *account = [[Account alloc] init];
account.accessToken = JSON[@"access_token"];
account.uid = JSON[@"uid"];
[[AccoundTool sharedAccoundTool] saveAccound:account];
*/
NSLog(@"成功--%@",JSON);
} failure:^(NSURLRequest *request, NSHTTPURLResponse *response, NSError *error, id JSON) {
NSLog(@"失败--%@",JSON);
}];
[op start];
//self.view.window.rootViewController = [[MainController alloc] init];
return NO;
}
//3.获取ACCESS TOKEN
return YES;
}

下一篇:THINKPHP 生成二维码