在下载 NSData dataWithContentsOfURL 时实现 UIActivityIndicatorView
我正在使用 NSData dataWithContentsOfURL:url 下载 mp3。这需要一段时间,并且在下载文件时应用程序会挂起。我想处理得很好,理想的情况是想显示下载进度,但找不到方法。
它位于 UIViewController 中,我第一次尝试放入 UIActivityIndicatorView 并在开始下载之前启动它旋转,然后停止它旋转,但什么也没有出现。
所以我的问题确实是请有人告诉我处理这个问题的最佳方法是什么?非常感谢
I am downloading an mp3 using NSData dataWithContentsOfURL:url. This takes a while and while the file is downloading the application hangs. I want to handle well and ideal would like to show the download progress but can't find methods for this.
It is in a UIViewController and I have made a first attempt by putting in a UIActivityIndicatorView and start it spinning before I start the download, then stop it spinning after but nothing appears.
So my question really is please could someone tell me what the best way to handle this is? Thanks so much
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不会出现任何内容,因为您的主线程在下载时被阻塞,而主线程是 UI 更新发生的地方。
您应该使用 NSUrlConnection 来下载异步并实现委托方法来启动/停止微调器。
或者,如果您想坚持使用
NSData
的dataWithContentsOfURL:url
您应该在单独的线程上执行此操作,并在调用之前和之后更新主线程上的微调器。Nothing will appear because your main thread is blocked doing the download, and the main thread is where UI updates occur.
You should use NSUrlConnection to download asynchronously and implement the delegate methods to start/stop your spinner.
Alternatively if you want to stick with
NSData
'sdataWithContentsOfURL:url
you should do this on a separate thread and update the spinner on the main thread before and after you call it.您可以在仍然使用同步方法的情况下实现此目的,但您需要在开始下载之前让运行循环有机会开始为活动指示器设置动画。
您可以通过使用延迟为 0 的performSelector:withObject:afterDelay: 在动画开始和下载之间放置一个运行循环来实现此目的,或者(更糟糕的风格,风险更大)您可以直接调用运行在您的代码中循环。
示例代码:
更多详细信息请参见:
http://bynomial.com/blog/?p=15
(向下滚动到解决方案 1 或解决方案 2)。
You can achieve this while still using synchronous methods, but you need to give the run loop a chance to start animating the activity indicator before you start the download.
You can achieve this by using either
performSelector:withObject:afterDelay:
with delay 0 to put a run loop between your animation start and the download, or (worse style, more risky) you can directly invoke the run loop within your code.Sample code:
More details here:
http://bynomial.com/blog/?p=15
(scroll down to Solution 1 or Solution 2).