如何在iOS中检查从互联网下载数据百分比?

时间:2012-07-18 12:26:48

标签: ios nsdata

我正在尝试将数据从互联网下载到iOS中的NSData。

当我从互联网上下载数据时,我看不到从服务器下载了多少百分比。

我没有使用UIWebView。

使用NSData从Internet下载声音(.mp3)。

我是否可以知道从互联网上下载了多少数据?

提前致谢。

2 个答案:

答案 0 :(得分:5)

步骤:

1)创建一个NSURLConnection,并请求.mp3的URL。

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 :(得分:0)

我建议你看一下:ASIHTTPRequest

您可以使用它和其他好东西轻松跟踪上传和下载过程。

塞巴斯蒂安

相关问题