Application response and NSURLConnection - ios

Does using lot of NSURLConnection blocks the UI/Main thread or does it slows down the responsive-ness of the app??? I've around max of 16 connections running at a time.The app becomes non-responsive after some time.One more doubt.. Do asynchronous NSURLConnection run on different thread???

I haven't found that in the documentation but i've already had problems running more than 4 NSURLConnection asynchronous in a project. Try to reduce the number to 2-3 and if not possible use NSOperation with NSOperationQueue.

Related

NSURLSession has NSoperationqueue internally?

A)If NSURLSession runs task in background in iOS7,Has Apple integrated internally Queue in NSURLSession?How it works in secondary thread and also in App suspended Mode?
B)What is the difference between NSURLSession and NSoperationqueue?
C)If NSURLSession is the replacement of NSURLCOnnection, Can we integrate NSURLSession into
NSOPerationqueue?
D)Are both same?
E)Can we do the same thing in NSURLSession as in NSoperationQueue?
f)is there any time limit to do task in background after closing application? because iOS7 does 2 min while ios6 does 10 min?
G)
Tutorial says under section Configuration and Limitation,NSURLSessionDataTasks are not supported in background sessions at all, and you should only use these tasks for short-lived, small requests, not for downloads or uploads.some tutorials are telling there is no time limit, we can download or upload data,the size may be whatever..Please explain more on this?
If NSURLSession is the relplacement of NSUrlconnection ,Which one is the best in all situations?What is the future of NSUrlconnection?
A) Yes, NSURLSession has its operation queue which maintains all the session tasks delegates in queue.
B) No, NSURLSession and NSOperationQueue has nothing for comparison. In fact, NSURLSession itself has a property of NSOperationQueue. NSURLSession is a replacement-API for NSURLConnection not NSOperationQueue.
C) There is no need of explicitly integrating it to NSOperationQueue. Every NSURLSession object has its own NSOperationQueue to perform its tasks concurrently.
D) Refer A,B,C
E) Again, this is a wrong comparison, NSURLSession is not replacement or equivalent for NSOperationQueue, it is replacement for NSURLConnection.
F) NSURLSession enables to use iOS7 background fetch mode with a background session configuration
[NSURLSessionConfiguration backgroundSessionConfiguration:#"identifier"];
If your question is about general background task execution, in iOS7 you can perform a task in background for 180.0 seconds. But for the background fetch request, you can fetch only for 30.0 seconds
G) Yes, Background fetch is basically designed for downloading/uploading stream of data at regular intervals managed by OS. OS provides the timeframe for your app periodically based on the available system resources. If your app cannot complete the download in 30.0 seconds, with NSURLSession the same task can be resumed next time.
NSURLSession is evolving and it has new priority request model also in iOS8, so I would suggest you to go with NSURLSession. It is asynchronous, it supports authentication handling, it supports separate cache storage, it supports periodic downloads and lot more.

iOS - Perform synchronous HTTP request with AFNetworking

I'm currently migrating my app from using ASIHTTPRequest to AFNetworking. I know synchronous requests are to be avoided if possible, but in my app I have just 1 place where I use one. In the app delegate applicationDidEnterBackground() method I need to run a HTTP request to query data to set the application badge number when the app goes to background. When run asynchronously this rarely works because the method just drops out and the application is suspended before the HTTP request completes. With ASIHTTPRequest I used the [request startSynchronous] method and this meant the HTTP request completed 100% every time and the badge was updated correctly. I see with AFNetworking there is no obvious synchronous option, so can anybody suggest a way it can be used synchronously, or an alternative solution?
Have found the way to do this - using one of the AFHTTPRequestOperation derivatives there is the method - setShouldExecuteAsBackgroundTaskWithExpirationHandler: which gives the operation extra time to complete before the OS suspends the app. So my code is :
[operation setShouldExecuteAsBackgroundTaskWithExpirationHandler:nil];
[operation start];
This was just what I needed and has solved my problem.
Jonathan
UPDATE: As Bob has pointed out using this method does not actually perform the operation synchronously, but was the ideal solution in my case in the absence of a synchronous method.

Do multiple NSURLConnections create multiple NSThreads?

NSURLConnection's documentation says that NSURLConnection is run on a separate thread and that delegate methods are called on a thread that started the connection.
I have more that one NSURLConnection objects wrapped in "URLDownload < NSURLConnectionDelegate >" objects which I run in parallel.
While pausing my program (at some time I put a breakpoint in it) and looking into Debug Navigator, I see only one com.apple.NSURLConnectionLoader thread.
Here is how I think this works:
I create 5 URLDownload object (each of them has its own NSURLConnection)
5 threads are created (one for each NSURLConnection)
Each NSURLConnection calls it's delegate methods on the thread that started them.
So there are 5 threads (one for each NSURLConnection) but their data (didReceiveData... method and others) is handled on a single thread.
Did I get this right?
Asynchronous NSURLConnection's will do there work off the main thread, that is all you need to know.
Threads use a lot of resources relative to the amount of work of a network connection, so 1 asynchronous NSURLConnection may use 1 background thread, 2 asynchronous NSURLConnections may use 2 background threads, but 100 asynchronous NSURLConnections probably won't use 100 background threads.
NSURLConnection is a black box that will manage the optimum amount for you. This could be based on how many processors you have, your network speed, etc (NB i'm not saying i know how it works under the hood, just that you don't need to know - it will do the right thing. One thread per connection would be a pretty horrible way todo it).
The delegate methods (didReceiveData, etc) get called on the thread that started the connection, so that isn't the same as saying that they are called on a single thread. If you start 5 connections on five different threads you will get the callbacks on five different threads.

NSURLConnection synchronous request from a thread vs asynchronous request

What is the differance between adding a operation which make a synchronous NSURLConnection request in NSOperationQueue ( or synchronous request from a thread ( not main thread)) AND making a asynchronous request from the main thread ?
Both will not block main thread so UI will remain responsive but is there any advantage of using one over other? I know in later method i can track request progress etc but assume that progress and other HTTP stuff is not important here.
They are very similar. The biggest problem with synchronous requests is that they can't easily be cancelled. Depending on your application, that could be a problem. Imagine you are downloading a big document and the user moves to another screen so you no longer need that information. In our case, I actually chose doing asynchronous NSURLConnections on a secondary NSThread, which may be overkill for some apps. It is more complicated, but it gives us the ability to both cancel requests and to decode the JSON/XML/image data on secondary threads so they don't impact main thread user interactivity.
Asynchronous requests are scheduled on the run loop and setup as a run loop source, triggering the code automatically only when there is data received from the network (as any socket source).
Synchronous requests running on a NSThread monopolizes a thread to monitor the incoming data, which is in general quite overkill.
You can always cancel an NSURLConnection even if it has been executed asynchronously, using the cancel method.
I bet using the new API that allows to send an asynchronous request on an NSOperationQueue (+sendAsynchronousRequest:queue:completionHandler:) uses GCD under the hood and dispatch_source_create, or something similar, so that it behave the same way as when an NSURLConnection is scheduled on the run loop, avoiding using an additional thread (watch the WWDC'12 videos that explains why threads are evil and their usage should be minimized), the difference only being that allows you to use a block to be informed upon completion instead of using the delegate mechanism.
Some years ago I created a class that embedded NSURLConnection asynchronous calls and delegate management into a nice block API (see OHURLLoader on my github) that makes it easier to use (feel free to take a look). I bet the new API that uses NSOperationQueues uses the same principle, still doing asynchronous requests on the runloop but allowing you to use blocks instead of having to implement a delegate.
The historical position was that there's an advantage in power consumption, and therefore battery life, in asynchronous requests — presumably including both the older delegate approach and the new block-based approach.

How do asynchronous NSURL requests fit with grand central dispatch / Operation queues ?

Can someone explain the relationship between asynchronous NSURL requests and GCD and NSOperationQueues?
I am not sure when to use each.
Right now, I have been "getting away" with asynchronous NSURL requests when I need to fetch/upload data to the server. But it has been suggested that I should use GCD. My problem is I do not know in what real life examples GCD would be better. Does anyone have any common use cases for me? And if I use GCD to store a queue of 10 asynchronous NSURL GET requests, for example, how would this benefit me? Does it even make sense to have an asynchronous NSURL request inside grand central dispatch queue or an NSOperationQueue?
Thank you!
What is particularly confusing in your case is that we're mixing an HTTP request queue (where requests would be sent one after the other) and an operation queue (where random computational work is executed one task after the other).
A standard NSURLConnection instance calls its delegate on the main thread, which is OK if you're not doing complex work on the data or on your UI at that time. But say you need to download a big file and write it chunk by chunk as a file on disk, all while scrolling down a table view. Now your scrolling might get choppy when you write data on the disk, blocking the main thread.
That's where GCD or its higher level abstraction NSOperationQueue comes into play. To solve this issue, you need to offload your data write calls off of the main thread. You can do that by specifying an NSOperationQueue instance on your NSURLConnection via setDelegateQueue:. This will ensure your delegate, and therefore your write calls, will be called in a background thread. You can also leave the delegate calls on the main thread, and wrap your expensive write calls inside a block which you will then execute off the main thread with dispatch_async. Now NSOperationQueue basically wraps a dispatch queue, and you're avoiding an extra thread switch by using it over a raw dispatch queue so I would recommend the NSOperationQueue solution (which also happens to looks simpler).
AFNetworking is a great library, and it solves this issue in a third way: it fires off an NSThread which is dedicated to NSURLConnection delegate calls. That's the pre-GCD way of offloading work off the main thread. Although it works, GCD offers a more efficient and good-citizen way of presenting your background work to the system.
Last, if you're looking for an HTTP request queue, Cocoa doesn't provide it. You will have to either build a scheduler yourself, or as you already figured it out use AFNetworking which again is a great choice.
If you're interested in this topic, GCD has a lot more to offer than just hosting NSURLConnection delegate calls, and I would recommend you read Apple's great Concurrency Programming Guide or watch the excellent WWDC 2011 videos on GCD (Blocks and Grand Central Dispatch in Practice and Mastering Grand Central Dispatch).
This is off the topic but if you use AFNetworking Lib you dont have to do anything you mentioned above.
"AFNetworking is a delightful networking library for iOS and Mac OS X. It's built on top of NSURLConnection, NSOperation, and other familiar Foundation technologies. It has a modular architecture with well-designed, feature-rich APIs that are a joy to use. "
Answer to your question, please read this
http://www.cocoaintheshell.com/2011/04/nsurlconnection-synchronous-asynchronous/

Resources