如何在 xcode 6 中立即将按钮更改为 activity 指示器

How to change instantly a button to an activity indicator in xcode 6

我正在尝试将导航栏中的按钮在按下时立即更改为 activity 指示器。我试过这段代码,但只有在 IBaction 进程结束时按钮才会改变:

- (BOOL)connected {
Reachability *reachability = [Reachability reachabilityForInternetConnection];
NetworkStatus networkStatus = [reachability currentReachabilityStatus];
return networkStatus != NotReachable;
}

- (IBAction)scaricaDatabase:(id)sender {
if (![self connected]) {
    _navTitle.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Non connesso" style:UIBarButtonItemStylePlain target:nil action:nil];
} else {
    UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    UIBarButtonItem * barButton = [[UIBarButtonItem alloc] initWithCustomView:activityIndicator];
    activityIndicator.color = [UIColor blackColor];

    // Set to Left or Right
    [activityIndicator startAnimating];
    [[self navTitle] setLeftBarButtonItem:barButton];

    NSString *dropboxHttpsUrl = @"https://dl.dropboxusercontent.com/u/68843065/eventiMedievale.sql";
    NSData *dbFile = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:dropboxHttpsUrl]];

    if(dbFile) {
        NSLog(@"%lu", (unsigned long)[dbFile length]);
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"eventiMedievaleUpd.sql"];
        [dbFile writeToFile:appFile atomically:YES];
        NSLog(@"%@", appFile);
        _navTitle.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Aggiornato" style:UIBarButtonItemStylePlain target:nil action:nil];
    }else{
        NSLog(@"File non scaricato");
    }
}

我需要在进程下载 sql 文件时显示 activity 指示符,但目前我只在该进程结束时更新导航栏。

有人可以帮我吗?

谢谢:)

我会尝试使用 Grand Central Dispatch 将 NSData 下载部分放入后台线程。这应该在您的 IBAction

范围内
UIActivityIndicatorView *activityIndicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
UIBarButtonItem * barButton = [[UIBarButtonItem alloc] initWithCustomView:activityIndicator];
activityIndicator.color = [UIColor blackColor];

// Set to Left or Right
[activityIndicator startAnimating];
[[self navTitle] setLeftBarButtonItem:barButton];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{ // 1
        //load the data here
        dispatch_async(dispatch_get_main_queue(), ^(void) {
            //remove the activity indicator 
        });
    });