0

我有一个应用程序需要下载声音文件才能正常工作。

我正在使用NSURLConnection异步下载超过 20Mb 的文件。我放置了一个progressBarView以跟踪下载百分比,并且我正在使用NSUrlConnectionApple 建议的委托方法。

NSURLRequest *theRequest=[NSURLRequest requestWithURL:soundFileURL cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0];
// create the connection with the request
// and start loading the data
NSURLConnection *theConnection;

theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

//[theConnection cancel];
//[theConnection start];
if (theConnection) {
    // Create the NSMutableData that will hold
    // the received data
    // receivedData is declared as a method instance elsewhere
    receivedData=[[NSMutableData data] retain];
} else {
    // inform the user that the download could not be made
} 

和委托方法

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [receivedData appendData:data];
}

所以 ...

当我开始下载时,界面不时progressView挂起,也挂起。

一件值得注意的事情,也许还有另一个问题:我禁用了用户界面,所以用户必须等到下载完成,当然,我给他一条消息告诉他。苹果会因此拒绝我的应用程序吗?我非常担心

感谢您阅读我的问题:)

4

2 回答 2

1

NSUrlConnection默认情况下将事件发送NSURLConnectionDelegate到主线程。您应该为此连接创建新的池和运行循环,并确保它在后台处理。这是在后台下载图像的示例。它使用修改后的 NSOperationQueue 和 NSOperation 但您可以轻松修改它以下载文件。developer.apple.com 上的 LinkedImageFetcher

于 2012-09-12T11:36:36.220 回答
0
 //1 First allocate NSOperationQueue object and set number of concurrent operations to execute at a time 

 NSOperationQueue *thumbnailQueue = [[NSOperationQueue alloc] init];
    thumbnailQueue.maxConcurrentOperationCount = 3;
// load photo images in the background
    __weak BHCollectionViewController *weakSelf = self;
    NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
        UIImage *image = [photo image];

        dispatch_async(dispatch_get_main_queue(), ^{
            // then set them via the main queue if the cell is still visible.

                cell.imageView.image = image;
            }
        });
    }];

    operation.queuePriority = (indexPath.item == 0) ?
        NSOperationQueuePriorityHigh : NSOperationQueuePriorityNormal;

    [thumbnailQueue addOperation:operation];

创建 NSObject 的 Photo 类并添加以下方法

- (UIImage *)image
{
    if (!_image && self.imageURL) {
        NSData *imageData = [NSData dataWithContentsOfURL:self.imageURL];
        UIImage *image = [UIImage imageWithData:imageData scale:[UIScreen mainScreen].scale];

        _image = image;
    }

    return _image;
}
于 2013-06-04T10:46:57.347 回答