Here是我的实际问题,正如一些人建议我想编写一个类来处理UITableView中的多个下载进度。我不知道如何为此写一个课程,有人可以提供一些技巧或想法吗?
答案 0 :(得分:0)
要查看的组是NSURLRequest和NSURLConnection。前者让你指定请求(URL,http方法,参数等),后者运行它。
由于您希望更新状态(I answered a sketch of this in your other question,我认为),您需要实现NSURLConnectionDelegate协议,该协议在从连接到达时移交数据块。如果你知道预期有多少数据,你可以使用收到的金额来计算我之前建议的downloadProgress浮点数:
float downloadProgress = [responseData length] / bytesExpected;
这是SO中的一些nice looking example code。你可以像这样扩展多个连接......
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
}
答案 1 :(得分:0)
我写了this库来做到这一点。您可以在github repo中签出实现。