开发者

Multiple NSUrlConnection Run Simultaneous

开发者 https://www.devze.com 2023-04-06 11:56 出处:网络
In my apps, there is a function which will download a file via HTTP URLConnection and write and append the data received to the files. That is some music files which needs couple minutes to complete t

In my apps, there is a function which will download a file via HTTP URLConnection and write and append the data received to the files. That is some music files which needs couple minutes to complete the download. During t开发者_C百科he download, user may need to request some other JSON data from the server.

And the problem is, what i am encountering is the request is delayed until the first connection (download the music file) is done. Both of it is separated to 2 different object and call by different class.

I do also try start them with NSThread

[NSThread detachNewThreadSelector: @selector(threadDownload) toTarget: self withObject: nil ];

However, the 2nd request is still waiting for the 1st request to be done, and because the downloading is taking too long time, the 2nd request get time out and error.

Hope for your opinion on how to overcome such issue?


Honestly I don't understand your complaints, since NSURLConnection is asynchronous by default, unless you are explicitly using sendSynchronousRequest:returningResponse:error:. For a "normal use", that is: initialize with initWithRequest:delegate: then call start, the class will handle all the process in a background thread and returns to the main thread only to invoke the designated delegate.


Use GCD, it is really easy, all the threading is done transparently.

Example:

__block NSMutableArray *imageURLList = [NSMutableArray array];

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

for (Helper *siteURL in list) {
    dispatch_async(queue, ^{
        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:siteURL]];
        NSURLResponse *response;
        NSError *error;
        NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
        if (urlData.length)
            [imageURLList urlData];
    });
}

Note that the block is executed async so it is alright to use sendSynchronousRequest:.

If a loop is does not work for you just make individual requests.


Best bet for this stuff is to use ASIHTTPRequest. It's easy to integrate and will handle all the concurrent background stuff for you.

Here's the url: http://allseeing-i.com/ASIHTTPRequest/


You can try this library called: ASIHTTPRequest, it can do lots of things (i just posted same answer to a questions few mins ago). You can have multiple requests (asynchronous), this should solve your problems. Its very easy to use.

0

精彩评论

暂无评论...
验证码 换一张
取 消