業(yè)務(wù)場(chǎng)景
今天和朋友在群里討論,他說需要在app最小化回來之后 刷新當(dāng)前頁面,也就是再次網(wǎng)絡(luò)請(qǐng)求。
方案
- 1 每個(gè)界面注冊(cè)通知,收到通知掉起網(wǎng)絡(luò),然后在appdelegate 最小化時(shí)候發(fā)送通知。
- 2 還是用通知,寫一個(gè)基類,所有controller繼承refreshNewWork方法
- 3 沒想到...??
第一種方法當(dāng)我們頁面特別多得時(shí)候 顯然有點(diǎn)不合理了,目前看起來第二種方案好像還可以。
首先看baseviewController方法
[self recieveDefaultcenter];
//通知
- (void)recieveDefaultcenter{
NSNotificationCenter *notiCenter = [NSNotificationCenter defaultCenter];
[notiCenter addObserver:self selector:@selector(receiveNotification:) name:@"refreshNetWork" object:nil];
}
- (void)receiveNotification:(NSNotification *)notify{
[self getCurrentViewController];
}
- (void)getCurrentViewController{
UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
UIViewController *currentVC = [self getCurrentVCFrom:rootViewController];
NSLog(@"當(dāng)前controller%@",[currentVC class]);
NSString *className = [NSString stringWithFormat:@"%@",[currentVC class]];
ViewControllerConst *viewConst = [ViewControllerConst shareViewConst];
NSArray *arr = [viewConst registViewControllers];
for (int i = 0; i<arr.count; i++) {
if ([className isEqualToString:arr[i]]) {
viewConst.isRefresh = YES;
}
}
[self refreshNewWork:className isRefresh:viewConst.isRefresh];
}
-(void)refreshNewWork:(NSString *)className isRefresh:(BOOL)isRefresh{
}
- (UIViewController *)getCurrentVCFrom:(UIViewController *)rootVC
{
UIViewController *currentVC;
if ([rootVC presentedViewController]) {
// 視圖是被presented出來的
rootVC = [rootVC presentedViewController];
}
if ([rootVC isKindOfClass:[UITabBarController class]]) {
// 根視圖為UITabBarController
currentVC = [self getCurrentVCFrom:[(UITabBarController *)rootVC selectedViewController]];
} else if ([rootVC isKindOfClass:[UINavigationController class]]){
// 根視圖為UINavigationController
currentVC = [self getCurrentVCFrom:[(UINavigationController *)rootVC visibleViewController]];
} else {
// 根視圖為非導(dǎo)航類
currentVC = rootVC;
}
return currentVC;
}
viewconst 是我建的一個(gè)類
4B46630E-39A3-4CD8-9D4E-AC8B1EC6F07A.png
想通過這個(gè)類 去過濾獲取到的viewcontroller
本來想這樣搞
ViewControllerConst *viewConst = [ViewControllerConst shareViewConst];
NSArray *arr = [viewConst registViewControllers];
for (int i = 0; i<arr.count; i++) {
if ([className isEqualToString:arr[i]]) {
viewConst.isRefresh = YES;
}
}
[self refreshNewWork:className isRefresh:viewConst.isRefresh];
這個(gè)過濾 有問題 永遠(yuǎn)會(huì)是yes 所以卡在這了
然后我在子類里面過濾了
-(void)refreshNewWork:(NSString *)className isRefresh:(BOOL)isRefresh{
NSString *currenClass = [NSString stringWithFormat:@"%@",[self class]];
if ([currenClass isEqualToString:className]) {
NSLog(@"首頁刷新");
}
}
為什么要判定,如果不判定 當(dāng)我點(diǎn)擊第二個(gè)界面最小化之后 第一個(gè)界面 還是會(huì)走刷新方法。
想知道各位有沒有什么好的方法實(shí)現(xiàn).