folex
folex

Reputation: 5297

connection:didReceiveResponse: from NSURLConnectionDelegate never fired

I'm trying to get UIProgressView, NSURLConnection, NSOperation and NSOperationQueue working together. Here is the code: http://pastie.org/4080576

Problem: connection:DidReceiveData: never called: execution going immediately to -start(), through -main(), then to -connection:DidReceiveResponse:, back to -main() (sometimes), and finally to -connectionDidFinishDownloading:destinationURL:.

When I trying to download picture from this link: http://upload.wikimedia.org/wikipedia/commons/4/41/Kharkov_picture_1787.jpg
I get this output:

2012-06-13 19:43:06.189 downloadingFilesInOpQueue[5070:f803] Received response: 2012-06-13 19:43:06.190 downloadingFilesInOpQueue[5070:f803] Filesize is: 3075638 Suggested filename is: Kharkov_picture_1787.jpg 2012-06-13 19:43:12.476 downloadingFilesInOpQueue[5070:f803] Finished downloading. Received 0 bytes

Also, I can't figure out where connection:didReceiveResponse: belong: NSURLConnectionDelegate or NSURLConnectionDataDelegate.

P.S. If there some style issues, I would glad to hear about them. Thx.

Upvotes: 0

Views: 716

Answers (1)

MechEthan
MechEthan

Reputation: 5703

I strongly suspect your "busy" while-loops are consuming the underlying run-loop's execution and choking out the NSURLConnection from being able to handle data as it arrives.

Looking at your pastie.org code, here's your primary culprits:

while (![self isFinished]) {
    ...
    while ([self fileSize] == 0) {}
    while ([self receivedDataLength] == 0) {}
    ...
}

Busy loops like this should almost never be used in iOS. iOS programming is largely event-driven, especially NSURLConnection. Instead, update your UIProgressView in response to connection:DidReceiveData: etc.

Honestly, coding your own NSURLConnection handlers is kind of a messy pain. I strongly recommend you look into using an open-source library that handles some of the difficulties. Here's two decent ones to check out:

  1. https://github.com/AFNetworking/AFNetworking
  2. https://github.com/pokeb/asi-http-request

Upvotes: 1

Related Questions