我正在尝试从互联网下载数据到iOS中的NSData。
当我从互联网上下载数据时,我看不到从服务器下载了多少百分比。
我没有使用UIWebView。
使用NSData从互联网下载声音(.mp3
)。
有没有办法让我知道从网上下载了多少数据?
提前谢谢。
发布于 2012-07-18 21:44:10
步骤:
1)创建一个请求到.mp3URL的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.
}
希望这能有所帮助。
干杯!
发布于 2012-07-18 20:38:43
我建议你看看这个:ASIHTTPRequest
你可以很容易地跟踪上传和下载过程与它和其他很好的东西。
塞巴斯蒂安
https://stackoverflow.com/questions/11541329
复制相似问题