只要你在你的UIViewController中持有對你的ASIHTTPRequest的引用,它就可以工作。
其次,你必須確保你的整個UIViewController不會被釋放,例如在UINavigationControllers中彈出非root用戶視圖控制器。
此外,在相關說明中,請參閱頁面頂部的here,該頁面不再積極開發ASIHTTPRequest。
編輯:
我用一個簡單的應用程序有兩個選項卡,加載時,其中第一的UIViewController立即開始下載測試這一點。由於ASIHTTPRequest在其自己的線程中異步運行,因此它會不斷更新進度欄,而不管它是否在視圖中。當我切換到第二個選項卡並在幾秒鐘後返回時,進度欄已進階。
// FirstViewController.h
#import <UIKit/UIKit.h>
#import "ASIHTTPRequest.h"
@interface FirstViewController : UIViewController {
IBOutlet UIProgressView *progressView;
ASIHTTPRequest *request;
}
@property (nonatomic,retain) ASIHTTPRequest *request;
@end
// FirstViewController.m
#import "FirstViewController.h"
@interface FirstViewController()
@end
@implementation FirstViewController
@synthesize request;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(@"First", @"First");
self.tabBarItem.image = [UIImage imageNamed:@"first"];
self.request = nil;
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
if (request==nil) {
request=[[ASIHTTPRequest alloc] initWithURL:[NSURL URLWithString:@"http://largefile.zip"]];
[request setDownloadProgressDelegate:progressView];
[request setShowAccurateProgress:YES];
[request shouldContinueWhenAppEntersBackground];
[request allowResumeForFileDownloads];
[request startAsynchronous];
}
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
} else {
return YES;
}
}
- (void) dealloc {
if (request!=nil) {
[request clearDelegatesAndCancel];
[request release];
}
}
@end
如上所述,另一種方法是將數據下載到單例中。單身,是授人以ASIHTTPRequest會再例如通過實施
- (void)request:(ASIHTTPRequest *)request didReceiveData:(NSData *)data;
,並呼籲
[[NSNotificationCenter defaultCenter] postNotificationName:@"MyCustomNotification" object:self];
再次通知你關於自定義通知的下載進度的UIViewController,因爲下載在自己的線程中運行即使它不在視圖中,你的UIViewController也會被通知。 UIViewController中有讓NSNotificationCenter知道,它想要通過調用
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(progressUpdate:)
name:@"MyCustomNotification"
object:nil];
最後要注意的接收通知,不要忘記調用
[[NSNotificationCenter defaultCenter] removeObserver:self];
當你的dealloc UIViewController中。
如何將ASIHTTPRequest的引用保存在獨立於您的VC的全局單例中? – Till 2012-04-27 13:39:14
但我也想保持progressview移動,這是否可能? – Mithuzz 2012-04-28 04:28:25