iOS - NSOperation中的异步NSURLConnection

时间:2013-02-25 12:03:05

标签: ios xcode cocoa-touch nsurlconnection nsoperation

我知道这个问题在SO上被多次询问过,但我没有设法让它在我的项目中运作......

所以,我想继承NSOperation并使用NSURLConnection下载文件。做正确的方法是什么? 这是我的代码不起作用: 首先,我在循环中添加所有操作:

DownloadFileOperation *operation;
NSOperationQueue *queue = [[NSOperationQueue alloc] init];
for (int i=0; i<10; i++) {
operation = [[DownloadFileOperation alloc] init];
operation.urlString = pdfUrlString;
[queue addOperation:operation];
operation = nil; }

这是我的子类:

@interface DownloadHandbookOperation : NSOperation <NSURLConnectionDelegate>
{

}

@property (strong, nonatomic) NSString *urlString;

@end


@implementation DownloadHandbookOperation
{
    NSString *filePath;
    NSFileHandle *file;
    NSURLConnection * connection;
}

- (void)start
{
    if (![NSThread isMainThread])
    {
        [self performSelectorOnMainThread:@selector(start) withObject:nil waitUntilDone:NO];
        return;
    }

    NSURL *url = [[NSURL alloc] initWithString:[self.urlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];

    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
    [req addValue:@"Basic ***=" forHTTPHeaderField:@"Authorization"];
    connection = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:YES];

}

- (void)connection:(NSURLConnection *)conn didReceiveResponse:(NSURLResponse *)response
{
    NSString *filename = [[conn.originalRequest.URL absoluteString] lastPathComponent];
    filename = [filename stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

    filePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:filename];
    [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];

    file = [NSFileHandle fileHandleForUpdatingAtPath:filePath] ;
    if (file)
    {
        [file seekToEndOfFile];
    }
    else
        [self finish];
}

- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data
{
    if (file) {
        [file seekToEndOfFile];
    }
    [file writeData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)conn
{
    [file closeFile];
    [self finish];
}

- (void)connection:(NSURLConnection *)conn didFailWithError:(NSError *)error
{
    connection = nil;

    [self finish];
}

- (void)cancel
{
    [super cancel];
    [connection cancel];
}


- (void)finish
{
    NSLog(@"operationfinished.");
}


@end

我做错了什么?

1 个答案:

答案 0 :(得分:8)

您需要正确配置您的操作以作为“并发操作”执行

Concurrency Programming Guide: Configuring Operations for Concurrent Execution

您需要返回isConcurrent = YES并以符合KVO的方式正确管理其他状态标记isExecutingisFinished


为了说明这里的一般想法,来自Pulse工程师的一篇文章描述了他们的解决方案,其中包含一些易于理解的演示代码,您可以下载和查看。

Pulse Engineering Blog: Concurrent Downloads using NSOperationQueues **

此代码还通过确保在主线程上启动NSURLConnection来处理NSURLConnection在具有活动runloop的线程上启动的要求。

(**现在链接到archive.org,我认为脉搏被收购并且已经将他们的旧网站关闭了)