iOS应用程序后台下载
嘿!我需要知道如何让我的 iOS 应用程序在应用程序后台开始下载(例如,在 AppDelegate 文件中运行下载),以便更改 ViewControllers 不会中断或取消下载。我还需要能够获取下载进度(0.00000 - 1.00000
),以设置 UIProgressView
对象,这也意味着我需要一个 - (void)progressDidChangeTo:(int)progress
函数。
Hey! I need to know how I can have my iOS Application start a download in the background of the application (like, have the download run in the AppDelegate file) so changing ViewControllers will not interrupt or cancel the download. I also need to be able to get the progress of the download (0.00000 - 1.00000
), to set a UIProgressView
object to, which also means I need a - (void)progressDidChangeTo:(int)progress
function.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只需使用 ASIHTTPRequest 它比 NSURLRequest 更容易,并且完全满足您的需要。
它示例展示了如何在后台下载以及如何报告进度。
我不会直接在 AppDelegate 中下载任何内容。相反,我会为此目的创建一个单独的类。我们将其命名为
MyService
然后,我将在我的应用程序委托中初始化该类。该类可以作为单例工作,也可以传递给需要它的每个视图控制器。
在 MyService 类中,我将添加 ASINetworkQueue 和一些方法来在请求准备好时处理请求。以下是您可以使用的 ASI 示例中的代码:
如果您需要设置进度条。我只需在 MyService 类中公开 ASINetworkQueue 的 setDownloadProgressDelegate 并将其设置在我的 ViewController 中,如下所示:
顺便说一句。如果您需要在应用程序退出时继续下载,您可以将请求的
ShouldContinueWhenAppEntersBackground
属性设置为 YES。Just use ASIHTTPRequest it is way easier than NSURLRequest and does exactly what you need.
It examples that shows how to download in background and how to report progress.
I wouldn't download anything in the AppDelegate directly. Instead I would create a separated class just for that purpose. Let's call it
MyService
I would then initialize that class in my app delegate.The class can work as a singleton or can be passed to each view controller that requires it.
In
MyService
class I would add the ASINetworkQueue and few methods to handle the requests when they are ready. Here is the code from ASI examples that you can use:If you need to set the progress bar. I would just expose the setDownloadProgressDelegate of ASINetworkQueue in my MyService class and set it in my ViewControllers like that:
BTW. If you need to continue downloading even when your app exits you can set
ShouldContinueWhenAppEntersBackground
property of your request to YES.您可以使用 NSURLConnection 启动异步请求,这不会导致您的 UI 被冻结。您可以通过执行以下操作来完成此操作:
为了获得进度,您可以使用:
委托调用来检查response.expectedContentLength,然后使用
来跟踪下载的数据量并计算百分比。
希望这有帮助,
莫西
you can use NSURLConnection to start an asynchronous request that won't cause your UI to be frozen. You can do it by doing something like:
in order to have your progress you can use the:
delegate call to inspect the response.expectedContentLength and then use the
to track the amount of data that was downloaded and calculate a percentage.
Hope this helps,
Moszi