Do I have to create NSOperation subclass for each web service? - ios

I always fetch data from web services using GCD. Now I have to use NSOperation and NSOperationQueue. But I am confused with the working of NSOperation and NSOperationQueue.
Suppose I have two APIs, Login API and Registration API. Do I have to create two NSOperation subclasses for it, like LoginOperation and RegistrationOperation? Or I could send various request in one NSOperation Class?
And how should I keep NSOperationQueue class central so that I keep adding operation class objects to it.
Please provide link for this type of sample project.

This will vary from project to project but generally you may want to have only one base subclass of NSOperation and subclass that for your specific requests such as LoginOperation or RegistrationOperation. You may want to look into AFNetworking since that is already a very well established networking library that subclasses NSOperation.
Depending on what you app is doing and how you want to manage your requests you may need more that one NSOperationQueue. This will help you keep track of the various requests and know if they have completed if needed, need to be syncronized, etc.
Have a look at this for something more in depth:
http://www.objc.io/issue-2/concurrency-apis-and-pitfalls.html

Related

Bolts framework task queue

I'm developing an iOS app and have been looking into using Bolts framework by Parse (facebook) to manage network operations (using Alamofire for network requests).
I'm wondering if there is a good implementation/pattern out there for a task queue for Bolts. I need to have offline functionality and therefore I (think) need to have some sort of task queue so if the user is offline all of their save/create operations are saved (queued and persisted) and then executed once they have a network connection, also needed for retries of requests. I've looked at NSOperation queue so I may go that route although I like how Bolts does things with BFTask and would prefer to use that.
I understand your problem, but I think that you mix up the purpose of NSOperation queue and BFTasks a little bit.
BFTasks are used in order to use and create asynchronous and synchronous methods/network requests in a cohesive and minimalistic way. For instance, suppose that would have to login a user, present a search view and then download user`s search query results.
In order to keep your app optimized and have the UI at 60fps you would need to run your network request asynchronously. Apparently, you would present search view only if user logged in (using your method) (this technique is called "async tasks in series") and then you would download search results using parallel async requests (Think about downloading movie artworks for a movie name query in iTunes. They start downloading at the same time, "in parallel" to each other, so user images are downloaded independently from each other). (Whereas this is one is called "async tasks in parallel").
As you can see from this example, we can only achieve the desired logic along with desired performance if we use sequential and parallel async requests.
Bolts framework allows you to achieve all of the aforementioned logic in a VERY cohesive and convenient way.
NSOperation queue, on the other hand, allow you to build a complex sequence of both sync and async methods. It even allows you to get the status of a particular operation and bind dependencies. A good example of it, is view controller lifecycle.
If I were you, I would first learn how to use Bolts and NSOperation queue apart from each other. Then, depending on what you actually need to achieve in your app in terms of functionality, I would start thinking about binding Bolts and NSOperation queue in a class or a struct (in case you use swift). Like using Bolts for "online" stuff (executing network requests) and NSOperation queue for "offline" (storing the sequence of actions the user makes while being offline, in order to execute this sequence when the internet connection is back).
You can read more about NSOperation here and about Bolts for iOS here.
UPDATE:
In terms of implementation pattern, one suggestion that you might want to consider is to create a simple class/struct that would be responsible for storing("stacking") your Bolts methods. You can use arrays for sequential logic and sets for parallel one. You can also use sets to easily make sure that some of the requests happen only once as sets store only unique objects. Honestly, in my opinion, you should try to implement something similar to what I described, because Bolts itself (almost for sure) incorporates NSOperation and NSOperaitionQueue.
By the way, since Parse iOS SDK is open source right now, you could see how they implement saveEvenutually method which saves an object when internet connection is back and think how you could replicate their logic according to your needs.

AFHTTPSessionManager calling Multiple Web service or batch with AFNetworking

I need to call multiple web services in a loop for uploading and downloading the data for application.(Known as Sync Process)
I am using AFHTTPSessionManager and create a subclass/wrappper class for that.
I need to do something in a que or creating batch request for that.
I am stuck at this from last night.
Thanks in advance.
For this kind of funcionalities probably an AFHTTPRequestOperationManager is a better choice.
SessionManager relies on tasks, tasks don't have the knowledge of dependency between each other, while operations does.
You have different possibilities:
Wrap sessions into a dispatch_group take a look here
Try to embed a session task inside an NSOperation (really hard)
Use AFHTTPOperation and add dependencies between operations
Use a serial queue on GCD
You might find also this answer helpful

Replacing NSURLConnection with NSURLSession

I have been starting a design for NetworkCommunication. I had a design where NSOperation subclasses create and manage their own NSURLConnection. The NSOperation subclass is instantiated by a NetworkManger class which adds it to the NSOperationQueue. Once the request is finished the delegate(ex:ViewController will be called). This is the flow:
The Network Manger instantiates NSOperation subclass (which encapsulates URL, parameters etc) and adds it to a NSOperationQueue it maintains.
NSOperation subclass instantiates NSURLConnection (which performs asynchronous request and retrieves data)
NSURLConnection dumps data to NSOperation-subclass
NSOperation-subclass executes the completion block supplied by the delegate( view controller).
I'm trying to implement the same pattern with NSURLSession now. I want to be able to encapsulate the url and parameters required to make a network request inside a single object.
Is it fine if i use the same pattern if I use NSURLSession. I checked AFNetworking classes. But, they have not subclassed NSOperation for NSURLSession. And, moreover where should the session object go. Will it be a part of the NSOperation class.
Can someone give some expert advice on this. I should be able to cancel requests, do uploading(POST/PUT), downloading of data. The Network Manager class would be the single point of contact for any network request.
Update:
NSURLConnection is deprecated effective Mac OS 10.11 and iOS 9. So, at this point NSURLSession should be used in lieu of NSURLConnection. As the NSURLConnection.h header says:
Deprecated: The NSURLConnection class should no longer be used. NSURLSession is the replacement for NSURLConnection.
My original answer is below.
The answer depends upon whether you need the richness of the various NSURLSession delegate methods or not. If you're ok using the completion block renditions (i.e. no progress callbacks, no streaming, etc.), the conversion from NSURLConnection to NSURLSession is pretty trivial. Just put your NSURLSession instance in your NetworkManager class, and then wrap the delegate based NSURLSessionTask instances in a concurrent NSOperation subclass and you're done. Just adopt the standard asynchronous/concurrent NSOperation subclass pattern.
If you're using the delegate-based renditions of NSURLSession, it's a whole different kettle of fish. The main hassle is that the various NSURLSessionTask delegate methods are called on the session delegate rather than a task delegate object. At first blush, this might sound like it's a trivial issue, but if your operation instances have unique completion/progress blocks, for example, you're stuck with the hassle of how to have the session object map these delegate method callbacks to the individual original request operation instances.
To tackle this, you have to maintain a mapping of task identifiers to your NSOperation subclass objects. You can then implement these NSURLSessionTask (including task, download task, and upload task) delegate methods at the respective NSOperation subclass. The NSURLSession network manager class can then, when it receives a NSURLSessionTask delegate call, use the task identifier to identify the appropriate NSOperation instance, and then call the appropriate delegate method there.
Finally, if you intend to handle background NSURLSession instances, life gets even more difficult (because background tasks will continue even after your app has terminated and all of its objects have been discarded). Background sessions simply don't lend themselves to an NSOperation-based approach.
Bottom line, this is trivial if you only need the completion-block NSURLSession methods, but it's a bit of a hassle if you need the delegate-based rendition.

Concurrency with AFNetworking Singleton

I have subclassed AFHTTPSessionManager and added some methods specific to my implementation. I have a couple questions around using my subclass as a singleton and concurrency:
Is creating a singleton of AFHTTPSessionManager still a best practice? (AFNetworking 2.0, iOS7)
If I make requests via a singleton of the subclass using the [self GET/POST method does this support concurrent
operations? E.g., I have a slow sync running and then do an search. Will the search begin immediately or wait for the sync to complete? Or, asked another way, are these operations on independent operation queues?
You asked:
Is creating a singleton of AFHTTPSessionManager still a best practice? (AFNetworking 2.0, iOS7)
I'm not sure if it ever was best practice. Singletons are frequently derided (see What's wrong with singleton?, which has links to lots of arguments against singletons). They are convenient, but for most apps, a singleton for the session manager is unnecessary. My general counsel is that you shouldn't use a singleton unless you have some compelling need to do so.
This is a subject of opinion and debate (which is explicitly frowned upon on Stack Overflow), so I would not suggest we pursue that question further. Follow the links in the above Stack Overflow question, and you'll see many opinions expressed there.
If I make requests ... does this support concurrent operations?
Yes, the network requests run asynchronously and support concurrent operations.
Are these operations on independent operation queues?
At the time I write this, the requests generated via AFHTTPSessionManager are not run on operation queues at all. The session's manager NSURLSession manages the tasks itself.
On the other hand, the NSURLConnection-based AFHTTPRequestOperationManager will run GET and POST requests on a single, concurrent operation queue. If you manually create your own AFHTTPRequestOperation, you can add them to your own queues if you want.
But all of this is academic. I think your real question is whether GET and POST requests run asynchronously, and the answer is "yes". And if the question is whether they run concurrently with respect to each other, again, the answer is "yes".

iOS equivalent of Android's ASyncTask to do Http Communications

I'm really new to IOS, in Android, I have a parent class Parent to define the basic http communication class, and a couple of subclasses(child1, child2) to really implement the functions.
Then put children (Parent p = new Child(xxx)) to ASyncTask(Parent xxx, xxxxx) and run it in doInBackground, then in onPostExecute, use some interfaces to update UI or do some other jobs.
So anyone knows how to implement similar structures in ios, I'll use AFNetworking-2.0 as networking lib instead of using Url Loading System.
It sounds like NSURLConnection is the equivalent, or the new NSURLSession class that was added in iOS 7.
NSURLConnection does async GET/PUT transactions. It handles managing the background networking, and then notifies you about progress on the main thread, which makes your code cleaner.
NSURLSession is a higher level API to manage whole networking tasks. I've read about it but haven't had occasion to use it yet.
It is a little different from Java.
Most developers have wrote her own URL Loading System Class to load asynchronous content.
This Guide from Apple will help u Loading Guide Apple

Resources