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回購中籤出實施。