Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
370 views
in Technique[技术] by (71.8m points)

iphone - networkActivityIndicatorVisible

Is this code correct to use with the networkActivityIndicatorVisible?

- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];

    UIApplication* app2 = [UIApplication sharedApplication]; 
    app2.networkActivityIndicatorVisible = YES; 
    [self loadSources];  // Loads data in table view
    app2.networkActivityIndicatorVisible = NO; 
}

Teo

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since NetworkActivityIndicatorVisible can be set from several points while a connection is still active, you need to track the number of calls that enable/disable it. The following UIApplication category does just that using a static variable:

// file UIApplication+NetworkActivity.h
@interface UIApplication (NetworkActivity)
- (void)showNetworkActivityIndicator;
- (void)hideNetworkActivityIndicator;
@end

// file UIApplication+NetworkActivity.m
#import "UIApplication+NetworkActivity.h"
static NSInteger activityCount = 0;
@implementation UIApplication (NetworkActivity)
- (void)showNetworkActivityIndicator {
    if ([[UIApplication sharedApplication] isStatusBarHidden]) return;
    @synchronized ([UIApplication sharedApplication]) {
        if (activityCount == 0) {
            [self setNetworkActivityIndicatorVisible:YES];
        }
        activityCount++;
    }
}
- (void)hideNetworkActivityIndicator {
    if ([[UIApplication sharedApplication] isStatusBarHidden]) return;
    @synchronized ([UIApplication sharedApplication]) {
        activityCount--;
        if (activityCount <= 0) {
            [self setNetworkActivityIndicatorVisible:NO];
            activityCount=0;
        }    
    }
}
@end

Now import UIApplication+NetworkActivity.h in your client code and call

// on connection started:
[[UIApplication sharedApplication] showNetworkActivityIndicator];

// on connection finished:
[[UIApplication sharedApplication] hideNetworkActivityIndicator];

If your concern is that the indicator blinks for only a second, you don't need a background process. Just call [self performSelector:@selector(loadSources) withObject:Nil afterDelay:0.1] so the UI thread has time to start the network indicator animation before you block the main thread.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...