IOSブログプロジェクト構築-09-OAuth 02ライセンス


データをキャプチャするには、Webサイトのライセンスが必要です.
一、登録sina授権権限の取得
https://api.weibo.com/oauth2/authorize?client_id=2699927613&redirect_uri=http://digtime.cn
このリンクは許可された後にcodeを返し、情報を取得します.
二、権限を作成するコントローラ、モデル、viewモジュール
  IOS博客项目搭建-09-OAuth02授权_第1张图片
#import "IWOAuthViewController.h"
#import "AFNetworking.h"
#import "IWAccount.h"
#import "IWTabBarViewController.h"
#import "IWNewfeatureViewController.h"

@interface IWOAuthViewController () <UIWebViewDelegate>

@end

@implementation IWOAuthViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // 1.  webView
    UIWebView *webView = [[UIWebView alloc] init];
    webView.frame = self.view.bounds;
    [self.view addSubview:webView];
    
    // 2.      (         )
    NSURL *url = [NSURL URLWithString:@"https://api.weibo.com/oauth2/authorize?client_id=2699927613&redirect_uri=http://digtime.cn"];   //    URL
    NSURLRequest *request = [NSURLRequest requestWithURL:url]; //    URL
    [webView loadRequest:request];
    
   }

三、webViewのすべての要求をブロックする
新浪授権後、ページは直接リダイレクトのアドレスにジャンプしますが、ここで授権後、codeコードを取得し、Tokenを取得し、リダイレクトのアドレスに直接ジャンプするのではなく、ユーザーのデータを取得することを望んでいます.そのため、ここではwebViewのロードを傍受する必要があります.そのため、webViewのすべての要求をブロックし、解決方法が必要です.エージェントを追加し、データをブロックできます.
IOS博客项目搭建-09-OAuth02授权_第2张图片
WebView自動リクエストのブロックhttp://digtime.cn/?code=8b1c66a777fe49b26fd650a4f2dacd98のパスを取得し、codeコードを切り取り、
codeコードでaccessTokenを取得します.
#pragma mark - webView    
/**
 *   webView                 ,               (  )
 *
 *  @param request
 *
 *  @return YES :       ,  NO :        
 */
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    // 1.   URL  
    NSString *urlStr = request.URL.absoluteString;
    
    // 2.         'code='  ,        ,       ,   code 
    // http://digtime.cn/?code=8b1c66a777fe49b26fd650a4f2dacd98
     NSRange range = [urlStr rangeOfString:@"code="];
    
    // 3.  urlStr    code=
    //  if(range.location != NSNotFound)
    if(range.length)
    {
        // 4.  code=       (         )
        int loc = range.location + range.length;
        NSString *code = [urlStr substringFromIndex:loc];
        
        // 5.  POST     ,  code    accessToken
        //                  
        // ASI:HTTP   ,     
        // AFN(AFNetworking)\AFN
       
        [self accessTokenWithCode:code];
        
    }
    
    NSLog(@"%@", request.URL);
    
    return YES;
    
}

四、AFN(AFNetworking)フレームワークを通してPOST要求を送信し、accessTokenを取得する
具体的な手順:
1.要求管理オブジェクトの作成
2.パッケージング要求パラメータ(パラメータは辞書でパッケージング)
3.要求を送信し、要求が成功した後、サーバー側はオブジェクトresponseObjectに応答する
4.ディクショナリをモデルに変換する(modelを作成し、IWAccount.hデータを取得してデータを置くのが便利)
5.モデルデータを格納---accessToken情報を格納---アーカイブ
5.1砂箱経路の取得
5.2ファイルパスの接続
    5.3 Account.h NSCodingプロトコルを遵守する必要があり、どの属性がアーカイブする必要があり、どの属性がアーカイブを解除する必要があるか
5.4そしてIWAppDelegate.mでは、アプリケーションのロードが完了した後、ユーザーが以前にログインに成功したかどうか、砂箱の中にデータがあるかどうかを判断し、砂箱のデータ授権情報が期限切れであるかどうかを判断し、期限切れでなければ直接微博に入る必要がある.
注意:IOSはサーバから返されたjsonを辞書に解析します.
codeによるaccessTokenメソッドの交換:
//  IWOAuthViewController.m

/**
 *    code    accessToken
 redirect_uri	true	string	    ,               。
 */
-(void)accessTokenWithCode:(NSString *)code
{
    //   POST     ,  code    accessToken
    //                  , ASI,AFN(       )
    // ASI:HTTP   ,     
    // AFN(AFNetworking)\AFN
     // 1.        
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    
    //          JSON
     mgr.responseSerializer = [AFJSONResponseSerializer serializer];
    
    // 2.      
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"client_id"] = @"2699927613";
    
    params[@"client_secret"] = @"737ea9bf1343d************";
    
    params[@"grant_type"] = @"authorization_code";
    
    params[@"code"] = code;
    
    params[@"redirect_uri"] = @"http://digtime.cn";
    
    
    // 3.    ,       ,               responseObject
    [mgr POST:@"https://api.weibo.com/oauth2/access_token" parameters: params
      success:^(AFHTTPRequestOperation *operation, id responseObject) {
          // IWLog(@"    :%@", [responseObject class]);        
          
          // 4.        (  model,IWAccount.h           )
          IWAccount *account = [IWAccount accountWithDict:responseObject];
          // NSString *accessToken =  responseObject[@"access_token"];
          
          //        ,        ,    ,     ,      
          // 5.      ---  accessToken   ---  
          // 5.1      
          NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
          // 5.2       
          NSString *file = [doc stringByAppendingPathComponent:@"account.data"];
          [NSKeyedArchiver archiveRootObject:account toFile:file];
          
          // 5.3 Account.h      NSCoding  ,        ,      
          // 5.4      IWAppDelegate.m          ,                ,       ,                 ,             
          
          // 6.      
          
          
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        IWLog(@"    :%@", error);

    }];
    
}

アカウントモデル:
 IWAccount.h
//
//  IWAccount.h
//  ItcastWeibo
//      

#import <Foundation/Foundation.h>

//      NSCoding  ,        ,      
@interface IWAccount : NSObject <NSCoding>
@property (nonatomic, copy) NSString *access_token;
//             ,    long long(    , ID)
@property (nonatomic, assign) long long expires_in;
@property (nonatomic, assign) long long remind_in;
@property (nonatomic, assign) long long uid;

+ (instancetype)accountWithDict:(NSDictionary *)dict;
- (instancetype)initWithDict:(NSDictionary *)dict;
@end

  IWAccount.m 
//
//  IWAccount.m
//  ItcastWeibo
//

#import "IWAccount.h"

@implementation IWAccount
+ (instancetype)accountWithDict:(NSDictionary *)dict{
    return [[self alloc] initWithDict:dict];
}

- (instancetype)initWithDict:(NSDictionary *)dict{
    if(self = [super init]){
        // KVC
        [self setValuesForKeysWithDictionary:dict];
    }
    return self;
}

//     1-             
-(id)initWithCoder:(NSCoder *)decoder{
    if(self = [super init]){
        self.access_token = [decoder decodeObjectForKey:@"access_token"];
        self.remind_in = [decoder decodeInt64ForKey:@"remind_in"];
        self.expires_in = [decoder decodeInt64ForKey:@"expires_in"];
        self.uid = [decoder decodeInt64ForKey:@"uid"];
    }
    
    return self;
}

//     2-            
-(void)encodeWithCoder:(NSCoder *)encoder{
    [encoder encodeObject:self.access_token forKey:@"access_token"];
    [encoder encodeInt64:self.remind_in forKey:@"remind_in"];
    [encoder encodeInt64:self.expires_in forKey:@"expires_in"];
    [encoder encodeInt64:self.uid forKey:@"uid"];
    
}


@end

プログラムエージェントIWAppDelegate.mでアカウント情報およびバージョン番号が格納されているか否かを判断する
//
//  IWAppDelegate.m
//  ItcastWeibo

#import "IWAppDelegate.h"
#import "IWTabBarViewController.h"
#import "IWNewfeatureViewController.h"
#import "IWOAuthViewController.h"
#import "IWAccount.h"

@implementation IWAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
    //            
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *file = [doc stringByAppendingPathComponent:@"account.data"];
    IWAccount *account = [NSKeyedUnarchiver unarchiveObjectWithFile:file];
    
    if (account) { //       
        NSString *key = @"CFBundleVersion";
        
        //                   
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        NSString *lastVersion = [defaults stringForKey:key];
        
        //           
        NSString *currentVersion = [NSBundle mainBundle].infoDictionary[key];
        
        if ([currentVersion isEqualToString:lastVersion]) {
            //      
            application.statusBarHidden = NO;
            self.window.rootViewController = [[IWTabBarViewController alloc] init];
        } else { //    
            self.window.rootViewController = [[IWNewfeatureViewController alloc] init];
            //      
            [defaults setObject:currentVersion forKey:key];
            [defaults synchronize];
        }
    } else { //         
        self.window.rootViewController = [[IWOAuthViewController alloc] init];
    }
    
    [self.window makeKeyAndVisible];
    return YES;
}

完全なライセンスコントローラmコード:
//
//  IWOAuthViewController.m
//  ItcastWeibo
//

#import "IWOAuthViewController.h"
#import "AFNetworking.h"
#import "IWAccount.h"
#import "IWTabBarViewController.h"
#import "IWNewfeatureViewController.h"

@interface IWOAuthViewController () <UIWebViewDelegate>

@end

@implementation IWOAuthViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // 1.  webView
    UIWebView *webView = [[UIWebView alloc] init];
    webView.frame = self.view.bounds;
    webView.delegate = self;
    [self.view addSubview:webView];
    
    // 2.      (         )
    NSURL *url = [NSURL URLWithString:@"https://api.weibo.com/oauth2/authorize?client_id=2699927613&redirect_uri=http://digtime.cn"];   //    URL
    NSURLRequest *request = [NSURLRequest requestWithURL:url]; //    URL
    [webView loadRequest:request];
    
   }


#pragma mark - webView    
/**
 *   webView                 ,               (  )
 *
 *  @param request
 *
 *  @return YES :       ,  NO :        
 */
-(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
{
    // 1.   URL  
    NSString *urlStr = request.URL.absoluteString;
    
    // 2.         'code='  ,        ,       ,   code 
    // http://digtime.cn/?code=8b1c66a777fe49b26fd650a4f2dacd98
     NSRange range = [urlStr rangeOfString:@"code="];
    
    // 3.  urlStr    code=
    //  if(range.location != NSNotFound)
    if(range.length)
    {
        // 4.  code=       (         )
        int loc = range.location + range.length;
        NSString *code = [urlStr substringFromIndex:loc];
        
        // 5.  POST     ,  code    accessToken
        //                  
        // ASI:HTTP   ,     
        // AFN(AFNetworking)\AFN
       
        [self accessTokenWithCode:code];
        
    }
    
    NSLog(@"%@", request.URL);
    
    return YES;
    
}


/**
 *    code    accessToken
 redirect_uri	true	string	    ,               。
 */
-(void)accessTokenWithCode:(NSString *)code
{
    //   POST     ,  code    accessToken
    //                  , ASI,AFN(       )
    // ASI:HTTP   ,     
    // AFN(AFNetworking)\AFN
     // 1.        
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    
    //          JSON
     mgr.responseSerializer = [AFJSONResponseSerializer serializer];
    
    // 2.      
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"client_id"] = @"2699927613";
    
    params[@"client_secret"] = @"737ea9bf1343****************";
    
    params[@"grant_type"] = @"authorization_code";
    
    params[@"code"] = code;
    
    params[@"redirect_uri"] = @"http://digtime.cn";
    
    
    // 3.    ,       ,               responseObject
    [mgr POST:@"https://api.weibo.com/oauth2/access_token" parameters: params
      success:^(AFHTTPRequestOperation *operation, id responseObject) {
          // IWLog(@"    :%@", [responseObject class]);        
          
          // 4.        (  model,IWAccount.h           )
          IWAccount *account = [IWAccount accountWithDict:responseObject];
          // NSString *accessToken =  responseObject[@"access_token"];
          
          //        ,        ,    ,     ,      
          // 5.      ---  accessToken   ---  
          // 5.1      
          NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
          // 5.2       
          NSString *file = [doc stringByAppendingPathComponent:@"account.data"];
          [NSKeyedArchiver archiveRootObject:account toFile:file];
          
          // 5.3 Account.h      NSCoding  ,        ,      
          // 5.4      IWAppDelegate.m        ,                ,       ,                 ,             
          
          // 6.      
          
          
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        IWLog(@"    :%@", error);

    }];
    
}

@end