0

Here是我的实际问题,因为一些人建议我想编写一个类来处理UITableView中的多个下载进度。我不知道如何为此撰写课程,有人可以提供一些提示或想法吗?如何编写更新下载进度的iOs

回答

0

要查看的组是NSURLRequest和NSURLConnection。前者让你指定请求(URL,http方法,参数等),后者运行它。

由于您想更新状态(我想是想更新状态(I answered a sketch of this in your other question)),您需要实现NSURLConnectionDelegate协议,该协议在连接到达时移交数据块。如果你知道有多少数据预期,你可以用收到的金额来计算downloadProgress浮动正如我前面建议:

float downloadProgress = [responseData length]/bytesExpected; 

下面是一些nice looking example code在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 
} 
+0

但在我的代码中,我在同一时间处理多个下载,我想单击一下按钮下载一组文件。所以我使用asinetworkqueue。所以我为队列设置了downloadp rogress委托。 – Mithuzz

+0

这是多个相同的模式。对不起,我没有注意到你的问题的这一方面。将编辑。 – danh

0

我写this库来这样做。您可以在github回购中签出实施。