下载进度条 [英] Progress bar while downloading

查看:100
本文介绍了下载进度条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序与应用内下载。我以这种方式成功下载mp3文件:

  NSData * data1 = [NSData dataWithContentsOfURL:[NSURL URLWithString:@http: /.../somefile.mp3\" ]]; 
[data1 writeToFile:filePath atomically:YES];

但是这个代码正在执行时真的很大的暂停。如何解决下载的进度并使用进度条显示?

解决方案

问题是 dataWithContentsOfURL:是一个阻塞调用。这意味着它会阻止它正在运行的线程。



你有几个选项来解决这个问题,而更好的是可能使用 NSURLConnection



使用 NSURLConnection 可以执行下载请求异步,这将阻止它阻止主线程。



您必须使用 NSURLConnectionDelegate 方法通知下载进度,保存数据,并通知成功或失败。



请阅读 NSURL加载系统



使用 NSURLConnection 的替代方法是使用调度队列对当前代码进行一些调用GCD。这将阻止通话阻止您的UI,但不允许您确定进度 - 因为您仍然需要使用 NSURLConnection


I have an app with in-app downloading. I successfully download mp3 files in this way:

NSData *data1 = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://.../somefile.mp3"]];
[data1 writeToFile:filePath atomically:YES];

But there is really big pause while this code is executing. How can I work out the progress of the download and display it with a progress bar?

解决方案

The problem is that dataWithContentsOfURL: is a blocking call. This means that it will block the thread that it is running on.

You've got a couple of options to fix this, and the better one is probably to use an NSURLConnection.

With an NSURLConnection you can perform the download request asynchronously, which will prevent it from blocking the main thread.

You must use the NSURLConnectionDelegate methods to be informed of the progress of the download, save its data, and to be informed of success or failure.

Please read the documentation for the NSURL Loading System.

An alternative to using NSURLConnection is to wrap your current code with some calls to GCD using dispatch queues. This will prevent the call from blocking your UI, but it will not allow you to determine the progress - for that you will still need to use NSURLConnection.

这篇关于下载进度条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆