码迷,mamicode.com
首页 > 移动开发 > 详细

iOS开发项目篇—21抽取工具类

时间:2014-07-13 10:08:32      阅读:207      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   使用   strong   

iOS开发项目篇—21抽取工具类

一、抽取宏

把和应用相关的信息抽取出来
App Key:1972915028
App Secret:b255603c4dfd82b4785bf9a808ce2662
(1)appkey和回调页面在很多地方都要用到
(2)如果是不同应用的话,只需要把这几个参数换掉就可以了。把它们抽取成一个宏,写到pch文件中。
项目的PCH文件
 1 #import <Availability.h>
 2 
 3 #ifndef __IPHONE_5_0
 4 #warning "This project uses features only available in iOS SDK 5.0 and later."
 5 #endif
 6 
 7 #ifdef __OBJC__
 8     #import <UIKit/UIKit.h>
 9     #import <Foundation/Foundation.h>
10     #import "UIImage+Extension.h"
11     #import "UIBarButtonItem+Extension.h"
12     #import "UIView+Extension.h"
13 
14 #ifdef DEBUG // 调试状态, 打开LOG功能
15 #define YYLog(...) NSLog(__VA_ARGS__)
16 #else // 发布状态, 关闭LOG功能
17 #define YYLog(...)
18 #endif
19 
20 // 颜色
21 #define YYColor(r, g, b) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:1.0]
22 
23 // 随机色
24 #define YYRandomColor [UIColor colorWithRed:arc4random_uniform(256)/255.0 green:arc4random_uniform(256)/255.0 blue:arc4random_uniform(256)/255.0 alpha:1.0]
25 
26 // 是否为iOS7
27 #define iOS7 ([[UIDevice currentDevice].systemVersion doubleValue] >= 7.0)
28 
29 //是否为4英寸
30 #define FourInch ([UIScreen mainScreen].bounds.size.height==568.0)
31 
32 // 导航栏标题的字体
33 #define YYNavigationTitleFont [UIFont boldSystemFontOfSize:20]
34 
35 //应用信息
36 #define YYAppKey     @"1972915028"
37 #define YYAppSecret   @"b255603c4dfd82b4785bf9a808ce2662"
38 #define YYRedirectURI  @"http://www.cnblogs.com/wendingding/"
39 #endif

二、抽取工具类

存在的问题:重复代码过多,可以考虑抽取出一个工具类。

新建一个工具类:

bubuko.com,布布扣

工具类头文件代码:

 1 //
 2 //  YYControllerTool.h
 3 //  12-微博抽取工具类
 4 //负责控制器相关的操作
 5 
 6 #import <Foundation/Foundation.h>
 7 
 8 @interface YYControllerTool : NSObject
 9 +(void)chooseRootViewController;
10 @end

工具类实现代码:

 1 //
 2 //  YYControllerTool.m
 3 //  12-微博抽取工具类
 4 //
 5 
 6 #import "YYControllerTool.h"
 7 #import "YYTabBarViewController.h"
 8 #import "YYNewfeatureViewController.h"
 9 
10 @implementation YYControllerTool
11 +(void)chooseRootViewController
12 {
13     UIWindow *window=[UIApplication sharedApplication].keyWindow;
14     NSString *versionKey=@"CFBundleVersion";
15     versionKey=(__bridge NSString *)kCFBundleVersionKey;
16     
17     //从沙盒中取出上次存储的软件版本号(取出用户上次的使用记录)
18     NSUserDefaults *defaults=[[NSUserDefaults alloc]init];
19     NSString *lastVersion=[defaults objectForKey:versionKey];
20     
21     //获得当前打开软件的版本号
22     NSString *currentVersion=[NSBundle mainBundle].infoDictionary[versionKey];
23     if ([currentVersion isEqualToString:lastVersion]) {//当前版本号==上次使用的版本号
24         window.rootViewController=[[YYTabBarViewController alloc]init];
25         //       self.window.rootViewController=[[YYNewfeatureViewController alloc]init];
26     }else{//当前版本号!=上次使用的版本号:显示新版本的特性
27         window.rootViewController=[[YYNewfeatureViewController alloc]init];
28         //存储这个使用的软件版本
29         [defaults setObject:currentVersion forKey:versionKey];
30         //立刻写入
31         [defaults synchronize];
32     }
33 
34 }
35 @end

在delegate文件中的使用:

 1 //
 2 //  YYAppDelegate.m
 3 //  Copyright (c) 2014年 itcase. All rights reserved.
 4 //
 5 
 6 #import "YYAppDelegate.h"
 7 #import "YYOAuthViewController.h"
 8 #import "YYControllerTool.h"
 9 
10 @implementation YYAppDelegate
11 
12 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
13 {
14  
15    //1.创建窗口
16     self.window=[[UIWindow alloc]init];
17     self.window.frame=[UIScreen mainScreen].bounds;
18     
19     //获取文件夹
20     NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
21     //获取写入的文件路径
22     NSString *filePath=[doc stringByAppendingPathComponent:@"account.plist"];
23     //获取信息,以进行判断
24     NSDictionary *account=[NSDictionary dictionaryWithContentsOfFile:filePath];
25     
26     //2.显示窗口(主窗口)
27     [self.window makeKeyAndVisible];
28     
29     //3.设置窗口的根控制器
30     if (account) {  //  存在成功授权的账号信息
31         [YYControllerTool chooseRootViewController];
32     }else  //没有登陆过
33     {
34         self.window.rootViewController=[[YYOAuthViewController alloc]init];
35     }
36   
37     return YES;
38 }
39 @end

在授权控制器中的使用:

  1 //
  2 //  YYOAuthViewController.m
  3 //
  4 
  5 #import "YYOAuthViewController.h"
  6 #import "MBProgressHUD+MJ.h"
  7 #import "AFNetworking.h"
  8 #import "YYTabBarViewController.h"
  9 #import "YYNewfeatureViewController.h"
 10 #import "YYControllerTool.h"
 11 
 12 @interface YYOAuthViewController ()<UIWebViewDelegate>
 13 
 14 @end
 15 
 16 @implementation YYOAuthViewController
 17 
 18 - (void)viewDidLoad
 19 {
 20     [super viewDidLoad];
 21     
 22     //1.创建UIWebView
 23     UIWebView *webView=[[UIWebView alloc]init];
 24     webView.frame=self.view.bounds;
 25     [self.view addSubview:webView];
 26 
 27     
 28     //2.加载登陆界面
 29     NSString *urlStr=[NSString stringWithFormat:@"https://api.weibo.com/oauth2/authorize?client_id=%@&redirect_uri=%@",YYAppKey,YYRedirectURI];
 30     NSURL *url=[NSURL URLWithString:urlStr];
 31     NSURLRequest *request=[[NSURLRequest alloc]initWithURL:url];
 32     [webView loadRequest:request];
 33     
 34     //3.设置代理
 35     webView.delegate=self;
 36 }
 37 
 38 #pragma mark-UIWebViewDelegate
 39 /**
 40  *  UIWebView开始加载资源的时候调用(开始发送请求)
 41  */
 42 -(void)webViewDidStartLoad:(UIWebView *)webView
 43 {
 44     [MBProgressHUD showMessage:@"正在努力加载中···"];
 45 }
 46 
 47 /**
 48  *  UIWebView加载完毕的时候调用(请求结束)
 49  */
 50 -(void)webViewDidFinishLoad:(UIWebView *)webView
 51 {
 52     [MBProgressHUD hideHUD];
 53 }
 54 
 55 /**
 56  *  UIWebView加载失败的时候调用(请求失败)
 57  */
 58 -(void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error
 59 {
 60     [MBProgressHUD hideHUD];
 61 }
 62 
 63 /**
 64  *  UIWebView每当发送一个请求之前,都会先调用这个代理方法(询问代理允不允许加载这个请求)
 65  *  @param request        即将发送的请求
 66  *  @return YES允许加载,NO不允许加载
 67  */
 68 -(BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
 69 {
 70     //1.获得请求地址
 71     NSString *urlStr=request.URL.absoluteString;
 72 //    NSLog(@"%@",urlStr);
 73     
 74     //2.判断url是否为回调地址
 75     //urlStr在字符串中的范围
 76     //设置从等号位置开始,不用再额外的找位置
 77     NSString *redirectURI=[NSString stringWithFormat:@"%@?code=",YYRedirectURI];
 78     NSRange range=[urlStr rangeOfString:redirectURI];
 79     //判断是否为回调地址
 80     if (range.location!=NSNotFound) {//是回调地址
 81         //截取授权成功后的请求标记
 82         int from=range.location+range.length;
 83         NSString *code=[urlStr substringFromIndex:from];
 84 //        YYLog(@"%@--%@--",urlStr,code);
 85         
 86         //根据code获得一个accessToken
 87         [self accessTokenWithCode:code];
 88         
 89         //禁止加载回调页面,拿到想要的东西就好了。
 90         return NO;
 91     }
 92     return YES;
 93 }
 94 /**
 95  *  根据code获得一个accessToken(发送一个Post请求)
 96  *  @param code 授权成功后的请求标记
 97  */
 98 -(void)accessTokenWithCode:(NSString *)code
 99 {
100     //1.获得请求管理者
101     AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
102     
103     //2.封装请求参数
104 
105     NSMutableDictionary *params=[NSMutableDictionary dictionary];
106     params[@"client_id"] =YYAppKey;
107     params[@"client_secret"] =YYAppSecret;
108     params[@"grant_type"] =@"authorization_code";
109     params[@"code"] =code;
110     params[@"redirect_uri"] =YYRedirectURI;
111     
112     //3.发送Post请求
113     [mgr POST:@"https://api.weibo.com/oauth2/access_token" parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary*responseObject) {
114         //隐藏遮罩
115         [MBProgressHUD hideHUD];
116         
117         //3.1存储授权成功的账号信息
118         //获取文件夹
119        NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)lastObject];
120         //获取写入的文件路径
121         NSString *filePath=[doc stringByAppendingPathComponent:@"account.plist"];
122         //保存信息,把字典数据存储到plist文件中
123         [responseObject writeToFile:filePath atomically:YES];
124         
125         //3.2切换控制器
126         [YYControllerTool chooseRootViewController];
127         
128         YYLog(@"请求成功");
129     } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
130         //隐藏遮罩
131          [MBProgressHUD hideHUD];
132         YYLog(@"请求失败");
133     }];
134 }
135 @end

 

iOS开发项目篇—21抽取工具类,布布扣,bubuko.com

iOS开发项目篇—21抽取工具类

标签:style   blog   http   color   使用   strong   

原文地址:http://www.cnblogs.com/wendingding/p/3837896.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!