这是我的实际问题,正如一些人建议的那样,我想编写一个类来处理 UITableView 中的多个下载进度。我不知道如何为此编写课程,有人可以提供一些提示或想法吗?
问问题
233 次
2 回答
0
要查看的组是 NSURLRequest 和 NSURLConnection。前者让您指定请求(URL、http 方法、参数等),后者运行它。
由于您想随时更新状态(我认为我在您的另一个问题中回答了这个草图),因此您需要实现 NSURLConnectionDelegate 协议,该协议在数据块从连接到达时移交它。如果您知道需要多少数据,您可以使用收到的数据量来计算我之前建议的 downloadProgress 浮点数:
float downloadProgress = [responseData length] / bytesExpected;
这是 SO 中一些漂亮的示例代码。您可以像这样扩展多个连接...
MyLoader.m
@interface MyLoader ()
@property (strong, nonatomic) NSMutableDictionary *connections;
@end
@implementation MyLoader
@synthesize connections=_connections; // add a lazy initializer for this, not shown
// make it a singleton
+ (MyLoader *)sharedInstance {
@synchronized(self) {
if (!_sharedInstance) {
_sharedInstance = [[MyLoader alloc] init];
}
}
return _sharedInstance;
}
// you can add a friendlier one that builds the request given a URL, etc.
- (void)startConnectionWithRequest:(NSURLRequest *)request {
NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
NSMutableData *responseData = [[NSMutableData alloc] init];
[self.connections setObject:responseData forKey:connection];
}
// now all the delegate methods can be of this form. just like the typical, except they begin with a lookup of the connection and it's associated state
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
NSMutableData *responseData = [self.connections objectForKey:connection];
[responseData appendData:data];
// to help you with the UI question you asked earlier, this is where
// you can announce that download progress is being made
NSNumber *bytesSoFar = [NSNumber numberWithInt:[responseData length]];
NSDictionary *userInfo = [NSDictionary dictionaryWithObjectsAndKeys:
[connection URL], @"url", bytesSoFar, @"bytesSoFar", nil];
[[NSNotificationCenter defaultCenter] postNotificationName:@"MyDownloaderDidRecieveData"
object:self userInfo:userInfo];
// the url should let you match this connection to the database object in
// your view controller. if not, you could pass that db object in when you
// start the connection, hang onto it (in the connections dictionary) and
// provide it in userInfo when you post progress
}
于 2012-06-18T03:26:20.797 回答
0
我写这个库就是为了做到这一点。您可以在 github 存储库中签出实现。
于 2016-12-16T18:09:40.603 回答