IOS第四天-新浪微博 -存储优化OAuth授权账号信息,下拉刷新,字典转模型
生活随笔
收集整理的這篇文章主要介紹了
IOS第四天-新浪微博 -存储优化OAuth授权账号信息,下拉刷新,字典转模型
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
*************application
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {// 1.創(chuàng)建窗口self.window = [[UIWindow alloc] init];self.window.frame = [UIScreen mainScreen].bounds;// 2.設置根控制器HWAccount *account = [HWAccountTool account];if (account) { // 之前已經登錄成功過 [self.window switchRootViewController];} else {self.window.rootViewController = [[HWOAuthViewController alloc] init]; //授權登陸的界面}// 3.顯示窗口 [self.window makeKeyAndVisible];return YES; }*************存儲賬號的信息HWAccountTool.m
// 賬號的存儲路徑 #define HWAccountPath [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"account.archive"]#import "HWAccountTool.h" #import "HWAccount.h"@implementation HWAccountTool/*** 存儲賬號信息** @param account 賬號模型*/ + (void)saveAccount:(HWAccount *)account {// 獲得賬號存儲的時間(accessToken的產生時間)account.created_time = [NSDate date];// 自定義對象的存儲必須用NSKeyedArchiver,不再有什么writeToFile方法 [NSKeyedArchiver archiveRootObject:account toFile:HWAccountPath]; }/*** 返回賬號信息** @return 賬號模型(如果賬號過期,返回nil)*/ + (HWAccount *)account {// 加載模型HWAccount *account = [NSKeyedUnarchiver unarchiveObjectWithFile:HWAccountPath];/* 驗證賬號是否過期 */// 過期的秒數(shù)long long expires_in = [account.expires_in longLongValue];// 獲得過期時間NSDate *expiresTime = [account.created_time dateByAddingTimeInterval:expires_in];// 獲得當前時間NSDate *now = [NSDate date];// 如果expiresTime <= now,過期/**NSOrderedAscending = -1L, 升序,右邊 > 左邊NSOrderedSame, 一樣NSOrderedDescending 降序,右邊 < 左邊*/NSComparisonResult result = [expiresTime compare:now];if (result != NSOrderedDescending) { // 過期return nil;}return account; } @end*******HWAccount.m
#import "HWAccount.h"@implementation HWAccount + (instancetype)accountWithDict:(NSDictionary *)dict {HWAccount *account = [[self alloc] init];account.access_token = dict[@"access_token"];account.uid = dict[@"uid"];account.expires_in = dict[@"expires_in"];return account; }/*** 當一個對象要歸檔進沙盒中時,就會調用這個方法* 目的:在這個方法中說明這個對象的哪些屬性要存進沙盒*/ - (void)encodeWithCoder:(NSCoder *)encoder {[encoder encodeObject:self.access_token forKey:@"access_token"];[encoder encodeObject:self.expires_in forKey:@"expires_in"];[encoder encodeObject:self.uid forKey:@"uid"];[encoder encodeObject:self.created_time forKey:@"created_time"]; }/*** 當從沙盒中解檔一個對象時(從沙盒中加載一個對象時),就會調用這個方法* 目的:在這個方法中說明沙盒中的屬性該怎么解析(需要取出哪些屬性)*/ - (id)initWithCoder:(NSCoder *)decoder {if (self = [super init]) {self.access_token = [decoder decodeObjectForKey:@"access_token"];self.expires_in = [decoder decodeObjectForKey:@"expires_in"];self.uid = [decoder decodeObjectForKey:@"uid"];self.created_time = [decoder decodeObjectForKey:@"created_time"];}return self; } @end*********HWAccount.h
#import <Foundation/Foundation.h>@interface HWAccount : NSObject <NSCoding> /** string 用于調用access_token,接口獲取授權后的access token。*/ @property (nonatomic, copy) NSString *access_token;/** string access_token的生命周期,單位是秒數(shù)。*/ @property (nonatomic, copy) NSNumber *expires_in;/** string 當前授權用戶的UID。*/ @property (nonatomic, copy) NSString *uid;/** access token的創(chuàng)建時間 */ @property (nonatomic, strong) NSDate *created_time;+ (instancetype)accountWithDict:(NSDictionary *)dict; @end?**********HWOAuthViewController.m
#import "HWOAuthViewController.h" #import "AFNetworking.h" #import "HWAccount.h" #import "HWAccountTool.h" #import "MBProgressHUD+MJ.h"@interface HWOAuthViewController () <UIWebViewDelegate>@end@implementation HWOAuthViewController- (void)viewDidLoad {[super viewDidLoad];// 1.創(chuàng)建一個webViewUIWebView *webView = [[UIWebView alloc] init];webView.frame = self.view.bounds;webView.delegate = self;[self.view addSubview:webView];// 2.用webView加載登錄頁面(新浪提供的)// 請求地址:https://api.weibo.com/oauth2/authorize/* 請求參數(shù):client_id true string 申請應用時分配的AppKey。redirect_uri true string 授權回調地址,站外應用需與設置的回調地址一致,站內應用需填寫canvas page的地址。*/NSURL *url = [NSURL URLWithString:@"https://api.weibo.com/oauth2/authorize?client_id=3235932662&redirect_uri=http://www.baidu.com"];NSURLRequest *request = [NSURLRequest requestWithURL:url];[webView loadRequest:request]; }#pragma mark - webView代理方法 - (void)webViewDidFinishLoad:(UIWebView *)webView {[MBProgressHUD hideHUD]; }- (void)webViewDidStartLoad:(UIWebView *)webView {[MBProgressHUD showMessage:@"正在加載..."]; }- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error {[MBProgressHUD hideHUD]; }- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {// 1.獲得urlNSString *url = request.URL.absoluteString;// 2.判斷是否為回調地址NSRange range = [url rangeOfString:@"code="];if (range.length != 0) { // 是回調地址// 截取code=后面的參數(shù)值int fromIndex = range.location + range.length;NSString *code = [url substringFromIndex:fromIndex];// 利用code換取一個accessToken [self accessTokenWithCode:code];// 禁止加載回調地址return NO;}return YES; }/*** 利用code(授權成功后的request token)換取一個accessToken** @param code 授權成功后的request token*/ - (void)accessTokenWithCode:(NSString *)code { /*URL:https://api.weibo.com/oauth2/access_token請求參數(shù):client_id:申請應用時分配的AppKeyclient_secret:申請應用時分配的AppSecretgrant_type:使用authorization_coderedirect_uri:授權成功后的回調地址code:授權成功后返回的code*/// 1.請求管理者AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager]; // mgr.responseSerializer = [AFJSONResponseSerializer serializer];// AFN的AFJSONResponseSerializer默認不接受text/plain這種類型// 2.拼接請求參數(shù)NSMutableDictionary *params = [NSMutableDictionary dictionary];params[@"client_id"] = @"3235932662";params[@"client_secret"] = @"227141af66d895d0dd8baca62f73b700";params[@"grant_type"] = @"authorization_code";params[@"redirect_uri"] = @"http://www.baidu.com";params[@"code"] = code;// 3.發(fā)送請求[mgr POST:@"https://api.weibo.com/oauth2/access_token" parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary *responseObject) {[MBProgressHUD hideHUD];// 將返回的賬號字典數(shù)據(jù) --> 模型,存進沙盒HWAccount *account = [HWAccount accountWithDict:responseObject];// 存儲賬號信息 [HWAccountTool saveAccount:account];// 切換窗口的根控制器UIWindow *window = [UIApplication sharedApplication].keyWindow;[window switchRootViewController];// UIWindow的分類、HWWindowTool// UIViewController的分類、HWControllerTool} failure:^(AFHTTPRequestOperation *operation, NSError *error) {[MBProgressHUD hideHUD];HWLog(@"請求失敗-%@", error);}]; } @endUIWindow+Extension.m
#import "UIWindow+Extension.h" #import "HWTabBarViewController.h" #import "HWNewfeatureViewController.h"@implementation UIWindow (Extension) - (void)switchRootViewController {NSString *key = @"CFBundleVersion";// 上一次的使用版本(存儲在沙盒中的版本號)NSString *lastVersion = [[NSUserDefaults standardUserDefaults] objectForKey:key];// 當前軟件的版本號(從Info.plist中獲得)NSString *currentVersion = [NSBundle mainBundle].infoDictionary[key];if ([currentVersion isEqualToString:lastVersion]) { // 版本號相同:這次打開和上次打開的是同一個版本self.rootViewController = [[HWTabBarViewController alloc] init];} else { // 這次打開的版本和上一次不一樣,顯示新特性self.rootViewController = [[HWNewfeatureViewController alloc] init];// 將當前的版本號存進沙盒 [[NSUserDefaults standardUserDefaults] setObject:currentVersion forKey:key];[[NSUserDefaults standardUserDefaults] synchronize];} } @end?************HWHomeViewController.m
#import "HWHomeViewController.h" #import "HWDropdownMenu.h" #import "HWTitleMenuViewController.h" #import "AFNetworking.h" #import "HWAccountTool.h" #import "HWTitleButton.h" #import "UIImageView+WebCache.h" #import "HWUser.h" #import "HWStatus.h" #import "MJExtension.h" // 第三方的框架@interface HWHomeViewController () <HWDropdownMenuDelegate> /*** 微博數(shù)組(里面放的都是HWStatus模型,一個HWStatus對象就代表一條微博)*/ @property (nonatomic, strong) NSMutableArray *statuses; @end@implementation HWHomeViewController- (NSMutableArray *)statuses {if (!_statuses) {self.statuses = [NSMutableArray array];}return _statuses; }- (void)viewDidLoad {[super viewDidLoad];// 設置導航欄內容 [self setupNav];// 獲得用戶信息(昵稱) [self setupUserInfo];// 集成刷新控件 [self setupRefresh]; }/*** 3. 集成刷新控件*/ - (void)setupRefresh {UIRefreshControl *control = [[UIRefreshControl alloc] init];[control addTarget:self action:@selector(refreshStateChange:) forControlEvents:UIControlEventValueChanged];[self.tableView addSubview:control]; }/*** 3-1 UIRefreshControl進入刷新狀態(tài):加載最新的數(shù)據(jù)*/ - (void)refreshStateChange:(UIRefreshControl *)control {// 1.請求管理者AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];// 2.拼接請求參數(shù)HWAccount *account = [HWAccountTool account];NSMutableDictionary *params = [NSMutableDictionary dictionary];params[@"access_token"] = account.access_token;// 取出最前面的微博(最新的微博,ID最大的微博)HWStatus *firstStatus = [self.statuses firstObject];if (firstStatus) {// 若指定此參數(shù),則返回ID比since_id大的微博(即比since_id時間晚的微博),默認為0params[@"since_id"] = firstStatus.idstr;}// 3.發(fā)送請求[mgr GET:@"https://api.weibo.com/2/statuses/friends_timeline.json" parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary *responseObject) {// 將 "微博字典"數(shù)組 轉為 "微博模型"數(shù)組NSArray *newStatuses = [HWStatus objectArrayWithKeyValuesArray:responseObject[@"statuses"]]; //第三方的框架// 將最新的微博數(shù)據(jù),添加到總數(shù)組的最前面NSRange range = NSMakeRange(0, newStatuses.count);NSIndexSet *set = [NSIndexSet indexSetWithIndexesInRange:range];[self.statuses insertObjects:newStatuses atIndexes:set];// 刷新表格 [self.tableView reloadData];// 結束刷新刷新 [control endRefreshing];} failure:^(AFHTTPRequestOperation *operation, NSError *error) {HWLog(@"請求失敗-%@", error);// 結束刷新刷新 [control endRefreshing];}]; }/*** 2. 獲得用戶信息(昵稱)*/ - (void)setupUserInfo {// 1.請求管理者AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];// 2.拼接請求參數(shù)HWAccount *account = [HWAccountTool account];NSMutableDictionary *params = [NSMutableDictionary dictionary];params[@"access_token"] = account.access_token;params[@"uid"] = account.uid;// 3.發(fā)送請求[mgr GET:@"https://api.weibo.com/2/users/show.json" parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary *responseObject) {// 標題按鈕UIButton *titleButton = (UIButton *)self.navigationItem.titleView;// 設置名字HWUser *user = [HWUser objectWithKeyValues:responseObject];[titleButton setTitle:user.name forState:UIControlStateNormal];// 存儲昵稱到沙盒中account.name = user.name;[HWAccountTool saveAccount:account];} failure:^(AFHTTPRequestOperation *operation, NSError *error) {HWLog(@"請求失敗-%@", error);}]; }/*** 1. 設置導航欄內容*/ - (void)setupNav {/* 設置導航欄上面的內容 */self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(friendSearch) image:@"navigationbar_friendsearch" highImage:@"navigationbar_friendsearch_highlighted"];self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(pop) image:@"navigationbar_pop" highImage:@"navigationbar_pop_highlighted"];/* 中間的標題按鈕 */HWTitleButton *titleButton = [[HWTitleButton alloc] init];// 設置圖片和文字NSString *name = [HWAccountTool account].name;[titleButton setTitle:name?name:@"首頁" forState:UIControlStateNormal];// 監(jiān)聽標題點擊 [titleButton addTarget:self action:@selector(titleClick:) forControlEvents:UIControlEventTouchUpInside];self.navigationItem.titleView = titleButton; }/*** 1-1 標題點擊*/ - (void)titleClick:(UIButton *)titleButton {// 1.創(chuàng)建下拉菜單HWDropdownMenu *menu = [HWDropdownMenu menu];menu.delegate = self;// 2.設置內容HWTitleMenuViewController *vc = [[HWTitleMenuViewController alloc] init];vc.view.height = 150;vc.view.width = 150;menu.contentController = vc;// 3.顯示 [menu showFrom:titleButton]; }- (void)friendSearch {NSLog(@"friendSearch"); }- (void)pop {NSLog(@"pop"); }#pragma mark - HWDropdownMenuDelegate /*** 下拉菜單被銷毀了*/ - (void)dropdownMenuDidDismiss:(HWDropdownMenu *)menu {UIButton *titleButton = (UIButton *)self.navigationItem.titleView;// 讓箭頭向下titleButton.selected = NO; }/*** 下拉菜單顯示了*/ - (void)dropdownMenuDidShow:(HWDropdownMenu *)menu {UIButton *titleButton = (UIButton *)self.navigationItem.titleView;// 讓箭頭向上titleButton.selected = YES; }#pragma mark - Table view data source - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {return self.statuses.count; }- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {static NSString *ID = @"status";UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];if (!cell) {cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:ID];}// 取出這行對應的微博字典HWStatus *status = self.statuses[indexPath.row];// 取出這條微博的作者(用戶)HWUser *user = status.user;cell.textLabel.text = user.name;// 設置微博的文字cell.detailTextLabel.text = status.text;// 設置頭像UIImage *placehoder = [UIImage imageNamed:@"avatar_default_small"];[cell.imageView sd_setImageWithURL:[NSURL URLWithString:user.profile_image_url] placeholderImage:placehoder];return cell; }/**1.將字典轉為模型2.能夠下拉刷新最新的微博數(shù)據(jù)3.能夠上拉加載更多的微博數(shù)據(jù)*/ @end?***HWTitleButton.h
#import "HWTitleButton.h"@implementation HWTitleButton- (id)initWithFrame:(CGRect)frame {self = [super initWithFrame:frame];if (self) {[self setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];self.titleLabel.font = [UIFont boldSystemFontOfSize:17];[self setImage:[UIImage imageNamed:@"navigationbar_arrow_down"] forState:UIControlStateNormal];[self setImage:[UIImage imageNamed:@"navigationbar_arrow_up"] forState:UIControlStateSelected];}return self; }- (void)layoutSubviews {[super layoutSubviews];// 如果僅僅是調整按鈕內部titleLabel和imageView的位置,那么在layoutSubviews中單獨設置位置即可// 1.計算titleLabel的frameself.titleLabel.x = self.imageView.x;// 2.計算imageView的frameself.imageView.x = CGRectGetMaxX(self.titleLabel.frame); }- (void)setTitle:(NSString *)title forState:(UIControlState)state {[super setTitle:title forState:state];// 只要修改了文字,就讓按鈕重新計算自己的尺寸 [self sizeToFit]; }- (void)setImage:(UIImage *)image forState:(UIControlState)state {[super setImage:image forState:state];// 只要修改了圖片,就讓按鈕重新計算自己的尺寸 [self sizeToFit]; } @end #import <UIKit/UIKit.h>@interface HWTitleButton : UIButton@end??HWStatus.h
#import <Foundation/Foundation.h> @class HWUser;@interface HWStatus : NSObject /** string 字符串型的微博ID*/ @property (nonatomic, copy) NSString *idstr;/** string 微博信息內容*/ @property (nonatomic, copy) NSString *text;/** object 微博作者的用戶信息字段 詳細*/ @property (nonatomic, strong) HWUser *user; @end?HWStatus.m
#import "HWStatus.h"@implementation HWStatus @end?
轉載于:https://www.cnblogs.com/ios-g/p/4828212.html
總結
以上是生活随笔為你收集整理的IOS第四天-新浪微博 -存储优化OAuth授权账号信息,下拉刷新,字典转模型的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java基础知识强化49:10个实用的但
- 下一篇: 第二次作业— —结对项目