iOS equivalent of Android's ASyncTask to do Http Communications - ios

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

Related

Best way to notify framework clients of state changes on iOS

I'm developing a framework for iOS apps that allows interfacing with custom BLE devices made by my company. We're planning to distribute the framework binary with public headers to clients. I've already designed the client facing interface, but it's lacking a major feature: notification on various different status conditions. That is, when the framework starts scanning for devices, connects to a device, reads data, uploads to our backend, etc, there is currently no way for client apps to know.
This has been fine for local testing, but before releasing, it would be best to add some functionality to allow clients to build a UI that updates based on these various status conditions. I'm not entirely sure of what the current, best way to do this is. I'm aware I can create an NSNotificationCenter and post notifications for each of these status changes, but I'm not sure if there is some better way of doing this? Should I accept a user callback? Expose some sort of listener protocol and ability register listeners? I'm sure others have solved this problem before, what have you found works well for iOS?
Use NSNotificationCenter for one to many communication, it notifies all the objects, which register to event, without knowing who throws it.
Use protocol and delegates for one to one object communication.
As per my experience you should go with delegates, it will be clean implementation and you can also define optional and required protocol.The the global class on client side can use this delegates, and update.

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.

Network traffic from a iOS SDK

Let's say I want to build a SDK that communicates with a server. I don't want any one (not even the app that implements the SDK) to intercept and look at my requests/responses.
If I'd use a common lib like AFNetworking it would be possible to look at all requests i.e by registering a NSURLProtocol.
I'm assuming that this would be harder to do if I would use i.e CFNetworking to perform my request/response handling? Or am I missing something? Would it be possible to intercept that traffic as well?
Using non NSURLConnection based classes, especially C low level classes (because NSIn/OutStream can be swizzled) like CFNetwork's CFStream, would make life harder for a potential curious developer. However, it will never stop a determined one. Your framework could, for example, be decompiled, although that's not a trivial task, which means many will quit even before starting, if the information is not worthwhile.

Async NSURLConnection triggering other Async NSURLConnection: what is the best way of doing this?

this is an open question aiming at understanding what is the best practice or the most common solution for a problem that I think might be common.
Let's say I have a list of URLs to download; the list is itself hosted on a server, so I start a NSURLConnection that downloads it. The code in connectionDidFinishLoading will use the list of URLs to instantiate one new NSURLConnection, asynchronously, per each URL; this in turn will trigger even more NSURLConnections, and so on - until there are no more URLs. See it as a tree of connections.
What is the best way to detect when all connections have finished?
I'm aiming the question to iOS7, but comments about other versions are welcome.
A couple of thoughts:
In terms of triggering the subsequent downloads after you retrieve the list from the server, just put the logic to perform those subsequent downloads inside the completion handler block (or completion delegate method) of the first request.
In terms of downloading a bunch of files, if targeting iOS 7 and later, you might consider using NSURLSession instead of NSURLConnection.
First, the downloading of files with a nice modest memory footprint is enabled by initiating "download" tasks (rather than "data" tasks).
Second, you can do the downloads using a background NSURLSessionConfiguration, which will let the downloads continue even if the user leaves the app. See the Downloading Content in the Background section of the App Programming Guide for iOS. There are a lot of i's that need dotting and t's that need crossing if you do this, but it's a great feature to consider implementing.
See WWDC 2013 What's New in Foundation Networking for an introduction to NSURLSession. Or see the relevent chapter of the URL Loading System Programming Guide.
In terms of keeping track of whether you're done, as Wain suggests, you can just keep track of the number of requests issued and the number of requests completed/failed, and in your "task completion" logic, just compare these two numbers, and initiate the "all done" logic if the number of completions matches the number of requests. There are a bunch of ways of doing this, somewhat dependent upon the details of your implementation, but hopefully this illustrates the basic idea.
Instead of using GCD you should consider using NSOperationQueue. You should also limit the number of concurrent operations, certainly on mobile devices, to perhaps 4 so you don't flood the network with requests.
Now, the number of operations on the queue is the remaining count. You can add a block to the end of each operation to check the queue count and execute any completion logic.
As Rob says in his answer you might want to consider NSURLSession rather than doing this yourself. It has a number of advantages.
Other options are building your own download manager class, or using a ready-made third party framework like AFNetworking. I've only worked with AFNetworking a little bit but from what I've seen its elegant, powerful, and easy to use.
Our company wrote an async download manager class based on NSURLConnection for a project that predates both AFNetworking and NSURLSession. It's not that hard, but it isn't as flexible as either NSURLSession or AFNetworking.

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

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

Resources