您的位置:首页 > 其它

1014-31-首页12-显示weibo未读数--后台运行---定时器

2016-03-11 21:51 253 查看
/**
* 当app进入后台时调用
*/
- (void)applicationDidEnterBackground:(UIApplication *)application
{
/**
* app的状态
* 1.死亡状态:没有打开app
* 2.前台运行状态
* 3.后台暂停状态:停止一切动画、定时器、多媒体、联网操作,很难再作其他操作
* 4.后台运行状态
*/
// 向操作系统申请后台运行的资格,能维持多久,是不确定的
UIBackgroundTaskIdentifier task = [application beginBackgroundTaskWithExpirationHandler:^{
// 当申请的后台运行时间已经结束(过期),就会调用这个block

// 赶紧结束任务
[application endBackgroundTask:task];
}];

// 在Info.plist中设置后台模式:Required background modes == App plays audio or streams audio/video using AirPlay
// 搞一个0kb的MP3文件,没有声音
// 循环播放

// 以前的后台模式只有3种
// 保持网络连接
// 多媒体应用
// VOIP:网络电话
}

----------------------------------------------------------------------------------------------------

- (void)test {

// 获得未读数
NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(setupUnreadCount) userInfo:nil repeats:YES];
// 主线程也会抽时间处理一下timer(不管主线程是否正在其他事件)
[[NSRunLoop mainRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

}

/**
* 获得未读数
*/
- (void)setupUnreadCount
{
// HWLog(@"setupUnreadCount");
// return;
// 1.请求管理者
AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];

// 2.拼接请求参数
HWAccount *account = [HWAccountTool account];
NSMutableDictionary *params = [NSMutableDictionary dictionary];
params[@"access_token"] = account.access_token;
params[@"uid"] = account.uid;

// 3.发送请求
[mgr GET:@"https://rm.api.weibo.com/2/remind/unread_count.json" parameters:params success:^(AFHTTPRequestOperation *operation, NSDictionary *responseObject) {
// 微博的未读数
// int status = [responseObject[@"status"] intValue];
// 设置提醒数字
// self.tabBarItem.badgeValue = [NSString stringWithFormat:@"%d", status];

// @20 --> @"20"
// NSNumber --> NSString
// 设置提醒数字(微博的未读数)
NSString *status = [responseObject[@"status"] description]; // 用 description 将 NSNumber 轻易转为 字符串对象
if ([status isEqualToString:@"0"]) { // 如果是0,得清空数字
self.tabBarItem.badgeValue = nil;
[UIApplication sharedApplication].applicationIconBadgeNumber = 0;
} else { // 非0情况
self.tabBarItem.badgeValue = status; // 在 tabBarItem 上显示未读数
[UIApplication sharedApplication].applicationIconBadgeNumber = status.intValue; // 在 应用图标 上显示未读数
}
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
HWLog(@"请求失败-%@", error);
}];
}

----------------------------------------------------------------------------------------------------
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: