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

Fir*_*ist 2 nsdata ios

我试图从互联网上下载数据到iOS中的NSData.

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

我没有使用UIWebView.

.mp3使用NSData从Internet 下载sound().

我还能知道从互联网上下载了多少数据吗?

提前致谢.

Geo*_*rge 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.
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.

干杯!