使用NSURLConnection运行NSOperation的多个实例?
我们有一个大型项目需要将大型文件从服务器同步到后台的“图书馆”中。 我读取子类NSOperation是多线程iOS任务中最灵活的方式,并且尝试过。 因此,该函数接收下载和保存的URL列表,初始化同一个NSOperation类的实例,并将其添加到NSOperation队列(每次只能下载一个文件)中。
-(void) LibSyncOperation {
// Initialize download list. Download the homepage of some popular websites
downloadArray = [[NSArray alloc] initWithObjects:@"www.google.com",
@"www.stackoverflow.com",
@"www.reddit.com",
@"www.facebook.com", nil];
operationQueue = [[[NSOperationQueue alloc]init]autorelease];
[operationQueue setMaxConcurrentOperationCount:1]; // Only download 1 file at a time
[operationQueue waitUntilAllOperationsAreFinished];
for (int i = 0; i < [downloadArray count]; i++) {
LibSyncOperation *libSyncOperation = [[[LibSyncOperation alloc] initWithURL:[downloadArray objectAtIndex:i]]autorelease];
[operationQueue addOperation:libSyncOperation];
}
}
现在,这些类实例都被创建好了,并且都被添加到NSOperationQueue并开始执行。 但问题是什么时候开始下载,第一个文件永远不会开始下载(使用委托方法使用NSURLConnection)。 我使用了另一个线程中看到的runLoop技巧,它应该允许操作在下载完成之前保持运行。 NSURLConnection已建立,但它从不开始将数据附加到NSMutableData对象!
@synthesize downloadURL, downloadData, downloadPath;
@synthesize downloadDone, executing, finished;
/* Function to initialize the NSOperation with the URL to download */
- (id)initWithURL:(NSString *)downloadString {
if (![super init]) return nil;
// Construct the URL to be downloaded
downloadURL = [[[NSURL alloc]initWithString:downloadString]autorelease];
downloadData = [[[NSMutableData alloc] init] autorelease];
NSLog(@"downloadURL: %@",[downloadURL path]);
// Create the download path
downloadPath = [NSString stringWithFormat:@"%@.txt",downloadString];
return self;
}
-(void)dealloc {
[super dealloc];
}
-(void)main {
// Create ARC pool instance for this thread.
// NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init]; //--> COMMENTED OUT, MAY BE PART OF ISSUE
if (![self isCancelled]) {
[self willChangeValueForKey:@"isExecuting"];
executing = YES;
NSURLRequest *downloadRequest = [NSURLRequest requestWithURL:downloadURL];
NSLog(@"%s: downloadRequest: %@",__FUNCTION__,downloadURL);
NSURLConnection *downloadConnection = [[NSURLConnection alloc] initWithRequest:downloadRequest delegate:self startImmediately:NO];
// This block SHOULD keep the NSOperation from releasing before the download has been finished
if (downloadConnection) {
NSLog(@"connection established!");
do {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
} while (!downloadDone);
} else {
NSLog(@"couldn't establish connection for: %@", downloadURL);
// Cleanup Operation so next one (if any) can run
[self terminateOperation];
}
}
else { // Operation has been cancelled, clean up
[self terminateOperation];
}
// Release the ARC pool to clean out this thread
//[pool release]; //--> COMMENTED OUT, MAY BE PART OF ISSUE
}
#pragma mark -
#pragma mark NSURLConnection Delegate methods
// NSURLConnectionDelegate method: handle the initial connection
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse*)response {
NSLog(@"%s: Received response!", __FUNCTION__);
}
// NSURLConnectionDelegate method: handle data being received during connection
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[downloadData appendData:data];
NSLog(@"downloaded %d bytes", [data length]);
}
// NSURLConnectionDelegate method: What to do once request is completed
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSLog(@"%s: Download finished! File: %@", __FUNCTION__, downloadURL);
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSString *targetPath = [docDir stringByAppendingPathComponent:downloadPath];
BOOL isDir;
// If target folder path doesn't exist, create it
if (![fileManager fileExistsAtPath:[targetPath stringByDeletingLastPathComponent] isDirectory:&isDir]) {
NSError *makeDirError = nil;
[fileManager createDirectoryAtPath:[targetPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:&makeDirError];
if (makeDirError != nil) {
NSLog(@"MAKE DIR ERROR: %@", [makeDirError description]);
[self terminateOperation];
}
}
NSError *saveError = nil;
//NSLog(@"downloadData: %@",downloadData);
[downloadData writeToFile:targetPath options:NSDataWritingAtomic error:&saveError];
if (saveError != nil) {
NSLog(@"Download save failed! Error: %@", [saveError description]);
[self terminateOperation];
}
else {
NSLog(@"file has been saved!: %@", targetPath);
}
downloadDone = true;
}
// NSURLConnectionDelegate method: Handle the connection failing
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
NSLog(@"%s: File download failed! Error: %@", __FUNCTION__, [error description]);
[self terminateOperation];
}
// Function to clean up the variables and mark Operation as finished
-(void) terminateOperation {
[self willChangeValueForKey:@"isFinished"];
[self willChangeValueForKey:@"isExecuting"];
finished = YES;
executing = NO;
downloadDone = YES;
[self didChangeValueForKey:@"isExecuting"];
[self didChangeValueForKey:@"isFinished"];
}
#pragma mark -
#pragma mark NSOperation state Delegate methods
// NSOperation state methods
- (BOOL)isConcurrent {
return YES;
}
- (BOOL)isExecuting {
return executing;
}
- (BOOL)isFinished {
return finished;
}
注意:如果这太难读了,我在这里设置了一个QUICK GITHUB PROJECT,您可以查看。 请注意,我并不期待任何人为我做我的工作,只是寻找我的问题的答案!
我怀疑它与保留/释放类变量有关,但我不能确定,因为我认为实例化一个类会为每个实例提供自己的一组类变量。 我已经尝试了一切,我找不到答案,任何帮助/建议将不胜感激!
更新:根据我下面的答案,我刚才解决了这个问题,并用工作代码更新了GitHub项目。 希望如果你来这里寻找相同的东西,它会有所帮助!
为了实现良好的社区实践并帮助其他任何可能最终出现同样问题的人,我最终解决了这个问题,并且更新了现在可以正常工作的GitHub示例项目 ,即使对于多个并发的NSOperations也是如此!
因为我做了大量的修改,所以最好查看一下GitHub代码,但是我必须做出的关键修复才能实现:
[downloadConnection scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
这是在NSURLConnection初始化之后调用的,并且在它启动之前调用。 它将连接的执行连接到当前的主要运行循环,以便在下载完成之前NSOperation不会过早终止。 我很想把这个聪明的解决办法发布在哪里,但是我已经忘记了在哪里,道歉了。 希望这可以帮助别人!
链接地址: http://www.djcxy.com/p/30595.html上一篇: Run multiple instances of NSOperation with NSURLConnection?