1. 開啟timer60秒請求一次微博數(shù)據(jù)宋梧。
2. 將timer添加到runloop上匣沼,不論主線程是否正在其他事件,都要抽時間處理一下timer捂龄。
3. 微博未讀數(shù):如果有未讀的微博條數(shù)释涛,要設(shè)置提醒數(shù)字,如果未讀數(shù)為0倦沧,得清空提醒數(shù)字唇撬。
開發(fā)代碼:
- (void)viewDidLoad
{
// 獲得未讀數(shù)
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(setupUnreadCount) userInfo:nil repeats:YES];
// 主線程也會抽時間處理一下timer(不管主線程是否正在其他事件)
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}
/**
*? 獲得未讀數(shù)
*/
- (void)setupUnreadCount
{
//? ? HWLog(@"setupUnreadCount");
//? ? return;
// 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://rm.api.weibo.com/2/remind/unread_count.json" parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary *responseObject) {
// 微博的未讀數(shù)
//? ? ? ? int status = [responseObject[@"status"] intValue];
// 設(shè)置提醒數(shù)字
//? ? ? ? self.tabBarItem.badgeValue = [NSString stringWithFormat:@"%d", status];
// @20 --> @"20"
// NSNumber --> NSString
// 設(shè)置提醒數(shù)字(微博的未讀數(shù))
NSString *status = [responseObject[@"status"] description];
if ([status isEqualToString:@"0"]) { // 如果是0,得清空數(shù)字
self.tabBarItem.badgeValue = nil;
[UIApplication sharedApplication].applicationIconBadgeNumber = 0;
} else { // 非0情況
self.tabBarItem.badgeValue = status;
[UIApplication sharedApplication].applicationIconBadgeNumber = status.intValue;
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
HWLog(@"請求失敗-%@", error);
}];
}