我有一个应用需要下载声音文件才能正常工作。
我正在异步使用NSURLConnection
来下载超过20Mb的文件。
我放置了一个progressBarView
来跟踪下载的百分比,我正在使用Apple建议的NSUrlConnection
委托方法。
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
也会挂起。
一个值得注意的事情,也许是另一个问题: 我禁用了用户界面,因此用户必须等到下载完成,当然,我给他一个消息告诉他。 Apple会拒绝我的应用吗?我非常担心
感谢您阅读我的问题:)
答案 0 :(得分:1)
NSUrlConnection
默认情况下将NSURLConnectionDelegate
的事件发送到主线程。您应该为此连接创建新池和runloop,并确保在后台处理它。以下是在后台下载图像的示例。它使用修改后的NSOperationQueue和NSOperation,但您可以轻松修改它以下载文件。 LinkedImageFetcher on developer.apple.com
答案 1 :(得分: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;
}