NSURLSession has NSoperationqueue internally? - ios

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.

Related

Continue background task after 3 minutes

I tried the answer of this question
How can a connection started with NSURLConnection while in the foreground be continued in the background?
And works like a charm! but only for 3 minutes in background, then iOS sends the app to sleep, Im trying to upload n videos and 3 minutes is not enought to send all data, I also readed that I can change my NSURLConnection to NSURLSession but I have no idea how to start that or how much time it takes.
Is there a way to keep background task alive after 3 minutes and until upload ends?
Is there a way to keep background task alive after 3 minutes and until upload ends?
No, there isn't. On-going background execution is limited to very narrow purposes (e.g. playing music, VOIP apps, navigation apps, etc.). All of this is outlined in the Background Execution section of the App Programming Guide for iOS.
I also [read] that I can change my NSURLConnection to NSURLSession but I have no idea how to start that or how much time it takes.
Yes, this is correct. If you want network request to continue for more than a few minutes after the app enters background, you should use NSURLSession with a background NSURLSessionConfiguration. See Downloading Content in the Background in the App Programming Guide for iOS for more information. See WWDC 2013 What's New in Foundation Networking for introduction to NSURLSession, including a demonstration on how to do background session.
I'd suggest you tackle this in two steps: First, convert to NSURLSession, and second, enable background NSURLSession operation. I think you'll find this first step is pretty easy. All of the concepts are very familiar. The only trick is that NSURLSession has two types of interfaces, delegate-protocol pattern and completion handlers. If you plan on using this for background operation later, you'll want to stick with the delegate-protocol pattern because the simpler completion handler pattern is not compatible with background sessions. And you'll want to use the upload task method that uploads from a file (don't use the stream-based rendition).
This second step, enabling background operation, isn't hard, but it can be tricky, though, simply because it involves a few new little details that we haven't had to worry about in the past (e.g. the app delegate code to capture (and later call) the completion handler for background sessions). Also, when you start debugging background session code, it can be disorienting to have requests initiated by one debugging session to show up in the next debugging session (hey, they're background sessions that are supposed to keep running when your app is terminated, after all). It's not a problem, but can be a bit disorienting.

NSOperation Queue vs NSUrlConnection async

I have an app that is downloading several photos off of Flickr. Right now, all the photos are downloaded with a custom NSOperation class run on an NSOperationQueue.However, I have heard about NSUrlConnection async being more efficient, and was wondering which is better of this situation? Or, is there a third option that's even better than these two?
The custom NSOperation simply calls [NSData dataWithContentsOfURL:] many times on different photos.
Using an approach which utilizes a subclass of NSOperation and which encapsulates NSURLConnection which is used in asynchronous mode (implementing the delegate protocols) is likely the most efficient, iff you additionally consider these aspects:
Ensure that the NSOperation subclass handles the delegate methods quickly, and that the underlaying thread (or the queue) will NOT be used to process the response data. Ideally, the delegate methods pass over the partial response data to another queue or thread where they are processed (note: image data may be preloaded on a background thread or a queue!).
The reason for this is that, the sooner the network operation finishes, the more requests can be performed per time. The network NSOperation shall be put into a NSOperationQueue whose max concurrent operations is set to 1, or 2. Rarely to 4 or higher. This setting depends on whether the server supports pipelining, and on the speed of the connection. Name that queue "Network bound queue".
The "data process" (preload image data) task is ideally a subclass of NSOperation, too. Likewise, the "data process" operations should be queued in a CPU bound NSOperationQueue. Per default the max concurrent operations of a NSOperationQueue is already suitable for CPU bound operations.
If you want to save the data to disk, again, ideally you create a NSOperation and queue those disk operations in a "disk bound queue". On devices, this seems not necessary, but if you have still such oldish "disks" - than it makes sense to set the number of max concurrent operations to the number of independent heads of the disk. ;)
Well, this all may make only a difference, when the connection is really fast and if you are able to process that much data in the same time. We are talking about 5 Mbyte per second on a device, and probably 25 Mbyte per second on a lab top.
Try these tutorials may help you:
http://maniacdev.com/2010/03/easier-threading-with-nsoperation-for-better-performance
http://www.raywenderlich.com/19788/how-to-use-nsoperations-and-nsoperationqueues
http://www.icodeblog.com/2012/10/19/tutorial-asynchronous-http-client-using-nsoperationqueue/
OR
If you are downloading photos and showing them in table cell, then you can use Lazy loading images.
I would recommend using AFNetworking (AFNetworking on Github)
which has built-in functionality for queuing operations.
If you only use it to load images that need to be displayed in a table view cell, you could use the AFNetworking category on UIImageView to load these images asynchronously.

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/

Application response and NSURLConnection

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.

Resources