只要你在你的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