UIScrollView滚动时NSURLRequest不会触发

13

我遇到了一个问题,我正在尝试在用户移动UIScrollView时后台加载声音文件...问题是我正在使用NSURLRequest进行后台加载,但即使如此,它也拒绝真正地加载,直到UIScrollView停止滚动。 :(

这个问题有什么解决办法吗?

谢谢!

2个回答

27

NSURLRequest 只负责管理请求, 而不是实际的连接.

触摸事件例如滚动操作会将运行循环置于 NSEventTrackingRunLoopMode, 默认情况下,NSURLConnection 仅被调度在 NSDefaultRunLoopMode 模式中执行. 因此,在 NSEventTrackingRunLoopMode 模式下,NSDefaultRunLoopMode 将被阻塞.

好消息是您可以为 NSURLConnection 调度其他模式,例如 NSRunLoopCommonModes.

connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
[connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
[connection start];

谢谢这个...帮我省了很大的麻烦!:-) NSEventTrackingRunLoopMode和NSRunLoopCommonModes有什么区别? - jowie
1
据我所知,安排在NSRunLoopCommonModes中的连接将被所有运行循环监视。如果它被安排在NSEventTrackingRunLoopMode中,则只会在有触摸事件时进行监视。http://developer.apple.com/library/ios/documentation/cocoa/reference/foundation/Classes/NSRunLoop_Class/Reference/Reference.html#//apple_ref/doc/uid/20000321-CJBJABGH - tidwall

1
我已经通过艰苦的方式发现,如果你调用startImmediately:YES或省略第二个参数,第二行代码将完全无效。所以一定要按照@tidwall提供的确切模式进行操作。
这里还有一个Swift示例:
self.connection = NSURLConnection(request: self.request, delegate: self, startImmediately:false)
self.connection?.scheduleInRunLoop(NSRunLoop.currentRunLoop(), forMode: NSRunLoopCommonModes)
self.connection?.start()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接