2012-07-18 85 views
2

我想從iOS上下載數據到NSData。如何在iOS中查看下載數據比例?

當我從互聯網上下載數據時,我看不到從服務器下載的百分比。

我沒有使用UIWebView。

從Internet與NSData下載聲音(.mp3)。

有沒有反正我可以知道從互聯網上下載了多少數據?

在此先感謝。

+0

你使用什麼下載方法? – 2012-07-18 12:30:26

+0

NSURLConnection – 2012-07-18 12:33:05

+2

實現NSURLConnectionDataDelegate。你會看到一個方法,告訴你整個包有多少個字節,現在有多少個字節。您應該將新數據附加到已下載的數據並計算百分比currentDataBytes/totalBytes。 – George 2012-07-18 12:44:57

回答

5

步驟:

1)創建於.MP3的URL請求的NSURLConnection的。

2)設置self作爲此連接的代表。

3)實現NSURLConnectionDataDelegate協議。 (旁邊添加到您的類的接口聲明

4)實現這些方法:

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
    NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; 
    statusCode = [httpResponse statusCode]; 
    if ((statusCode/100) == 2) 
    { 
     contentLength = [httpResponse expectedContentLength]; 
     if (contentLength == NSURLResponseUnknownLength) 
       NSLog(@"unknown content length %ld", contentLength); 
    } 

} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 
    bytesSum += [data length]; 
    percent = (float)bytesSum/(float)contentLength; 

    // append the new data to the receivedData 
    [receivedData appendData:data];  //received data is a NSMutableData ivar. 

} 

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    //the end. Write your data (stored in receivedData) to a local .mp3 file. 
} 

希望這有助於。

乾杯!

+1

嗨,「+ =」中有錯誤。 – 2012-07-18 13:59:26

+1

錯誤?你是否聲明瞭ivar'long bytesSum'(在你的課堂上)? – George 2012-07-18 14:08:31

+0

只是好奇,爲什麼你將'statusCode'除以100並檢查2?爲什麼不檢查200? – Undo 2013-07-24 17:52:50

0

我建議看看這個:ASIHTTPRequest

你可以很容易與它和其他不錯的東西跟蹤上傳和下載過程。

塞巴斯蒂安

+1

即使是ASIHTTPRequest的開發者也不建議你再使用它http://allseeing-i.com/[request_release]; – Abizern 2012-07-19 08:14:09