#import "ViewController.h"
#import "AFNetworking.h"@interface ViewController ()<UIWebViewDelegate>@end@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; //1.使用webview UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.bounds]; [self.view addSubview:webView]; //要讓webView發起請求 我需要一個新浪的登錄頁面 //接口 https://api.weibo.com/oauth2/authorize 這個接口. //使用那個平臺,就要使用哪個平臺的sdk 只需要提供三個參數 app key ,app sercect?,回調頁網址. /** client_id 申請應用時分配的AppKey。 redirect_uri 授權回調地址,站外應用需與設置的回調地址一致,站內應用需填寫canvas page的地址。 */ NSURL *url = [NSURL URLWithString:@"https://api.weibo.com/oauth2/authorize?client_id=2320601559&redirect_uri=http://www.baidu.com"]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; webView.delegate = self; [webView loadRequest:request]; //當用戶點擊授權的時候,新浪服務器返回一個重定向地址,并且綁定了一個重要的參數 code //code是干嘛的?,demo應用要找到這個code 然后用這個code去新浪服務器去請求toke}- (void)webViewDidStartLoad:(UIWebView *)webView { NSString *url = webView.request.URL.absoluteString; NSLog(@"webview開始加載,加載地址是 : %@",url);}- (void)webViewDidFinishLoad:(UIWebView *)webView { NSLog(@"webView加載結束");}- (BOOL) webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { //判斷一下請求是否是服務器返回的重定向請求? NSString *url = request.URL.absoluteString; //是否包含code= NSRange range = [url rangeOfString:@"code="]; if (range.length != 0) { //這里就要截取code=后面的數據.// http://www.baidu.com/?code=29a7addea0226eeaf94768440639189f NSInteger index = range.location + range.length; NSString *code = [url substringFromIndex:index]; //自己發起一個請求獲取access_token /** client_id string 申請應用時分配的AppKey。 client_secret string 申請應用時分配的AppSecret。 grant_type string 請求的類型,填寫authorization_code grant_type為authorization_code時 必選 類型及范圍 說明 code string 調用authorize獲得的code值。 redirect_uri string 回調地址,需需與注冊應用里的回調地址一致。 */ AFHTTPsessionManager *sessionManager = [AFHTTPSessionManager manager]; NSString *tokenURL = @"https://api.weibo.com/oauth2/access_token"; NSDictionary *params = @{ @"client_id":@"2320601559", @"client_secret":@"d77590e7cb2b4dda50e5c17359380d0e", @"grant_type":@"authorization_code", @"code":code, @"redirect_uri":@"http://www.baidu.com" }; [sessionManager POST:tokenURL parameters:params success:^(NSURLSessionDataTask *task, id responSEObject) { NSLog(@"token 請求成功 %@",responseObject);// 2.00aE6vVD6TADXCd89cbb1e870CqJn_ NSDictionary *result = (NSDictionary *)responseObject; NSString *token = result[@"access_token"]; [sessionManager GET:@"https://api.weibo.com/2/statuses/public_timeline.json" parameters:@{@"access_token":token} success:^(NSURLSessionDataTask *task, id responseObject) { NSLog(@"成功返回的地址是 : %@",responseObject); } failure:^(NSURLSessionDataTask *task, NSError *error) { NSLog(@"返回失敗."); }]; // 2.00aE6vVD6TADXCd89cbb1e870CqJn_ } failure:^(NSURLSessionDataTask *task, NSError *error) { NSLog(@"token 請求失敗."); }]; //阻止當前webviwe跳轉到回調頁面. return NO; } return YES;}@end
新聞熱點
疑難解答