Callback from static library - iphone

I think this should be simple, but im having a real hard time finding information about this topic. I have made a static library and have no problem getting the basics to work. But im having a hard time figuring out how to make a call back from the static library to the main APP.
I would like my static library to only use one header as front, this header should contain functions like:
requestImage:(NSString *)path;
requestLikstOfSomething:(NSSting *)guid;
and so on..
These functions should do the necessary work and start a async NSURLConnection, and call back to the main application when the call have finished. How do you guys do this, what are the best ways to callback from a static library when a async method is finished? should i do this with delegates (is this possible), notifications, key/value observers. I really want to know how you guys have solved this, and what you regard as the best practices.
Im going to have 20-25 different calls so i want the static library header file to be as simple as possible preferable only with a list of the 20-25 functions.
UPDATE:
My question is not how to use delegate pattern, but witch way is the best to do callbacks from static librarys. I would like to use delegates but i dont want to have 20-25 protocol declarations in the public header file. I would prefer to have only one function for each request.
Solution choosen:
i choose the solution from erkanyildiz with the help of a target parameter, i know its pretty low tech, but it was for me the cleanest solution. My goal was to keep the header file as small as possible. Thanks to everybody for they input, i will for sure look more into borrrdens solution with grand central dispatch when i get the time. user1055604 solution with a couple of "standard" delegates for replys is also one i like. So again thank you all for inputs.
Thanks in advance.
Best regards
Morten

Delegation pattern is a good way to do it.
You can check these pages:
http://developer.apple.com/library/ios/documentation/Cocoa/Conceptual/CocoaFundamentals/CommunicatingWithObjects/CommunicateWithObjects.html#//apple_ref/doc/uid/TP40002974-CH7-SW18
http://en.wikipedia.org/wiki/Delegation_pattern#Objective-C_example
As another approach, you can use a target parameter in every method you have.
And schedule callbacks on those targets, checking if they are responding to your callbacks using respondsToSelector

Look here for an example with delegates: How to perform Callbacks in Objective-C.
It shouldn't matter that the callback is executing from within a static library.
Static libraries are a compile/link time phenomenon. As such, calls to and from within static libraries are transparent to the application at runtime.

If you would rather not have one callback protocol declaration for each function in your static library, start with looking at what each callback would return if you did, forcefully, implement it as a callback.
From there on, find what's in common between them and bind the common elements together in a class which will serve as an interface for the responses. You may need more that one such class.
As an example, look at NSURLResponse:
NSURLResponse declares the programmatic interface for an object that accesses the response returned by an NSURLRequest instance.
NSURLResponse encapsulates the metadata associated with a URL load in a manner independent of protocol and URL scheme.
This class is used by NSURLConnection in its didReceiveResponse delegate method. In the worse case, you will end up with a couple of callbacks instead of a noisy header file. Happy coding. :-)

Try making your function calls using Grand Central Dispatch. It's quite simple, and very powerful. Here is a sample of how to make an async call with a callback:
http://pastebin.com/xDUKm6wh
This paste bin is complaining about errors, but take note of the pattern. It should work just fine.

Related

NotificationCenter or Closure?

For the supervisors: I have searched a lot before I decided to ask
this question but I didn't find exactly what I want.
My question is: Which is better between using NotificationCenter and using Closures to communicate between two instances?
If they are similar, what should I use?
Hopefully, this example helps you to understand better:-
If we take URLSession class as an example. Why do most of its methods have a closure? Why do not they send a notification with Data, Response, and Error inside it?
I know the difference between them, I just don't know in what situations should I use each one.
In some cases the patterns are interchangeable, however:
Using a closure is the simplest solution for simple cases
Using a delegate is common when there is complex communication between two objects. One delegate can be better than many closures.
You have to use notifications when you have multiple observers or when you are not sure what objects will be observing.
You might be asking yourself why we are using closures for simple cases and not delegates or notifications. The answer is that closures are the most lightweight. They are easy to create and they positively affect your code quality.
Let's consider a completion callback. If you decide to use a notification, you need another method that will handle that notification. The same is valid for delegates. If you need some context (e.g. the parameters that triggered the actions), you will need to save it into a property.
On the other hand, a closure can be created inline. That means that the code that triggers the action and handles its result is at one place. This really simplifies the structure of your code. Also note that if the closure needs some context, it can capture it, without the need to create an additional property.

How do I make a reusable web interface class in objective C?

I'm working on a new iPhone/iPod app that includes the need to do web services requests. I've found methods for doing these requests synchronously, or asynchronously by setting the controller as the delegate. What I'd really like to be able to do, though, is to create a single class that can handle all web requests for the whole application, and just create an instance of that class when I need to use it. That way, cookies and common pieces of code can be handled in one place, rather than all over the app.
So far the only thing I thought of that could accomplish what I'm trying to do is to create a new thread that handles the request synchronously within itself, then sends a message back to the calling controller once the request is complete. Is there a better way to accomplish what I'm trying to do?
Cookies are already a shared resource.
I would suggest reading the URL Loading System Overview to get an idea of how Apple set everything up. From what you describe, you want something very similar to how they have set up the system, maybe with a Singleton class for the connection. You can also look at ASIHTTPRequests which is a good wrapper around all of the connections stuff.
I would not suggest writing my own code here. Lots and lots of people have solved this problem for you.

iOS/Objective-C Multiple URL Connections

I have a few apps that I am trying to develop a reusable URL connection layer. I have done some research and am struggling between architectures. Specifically the APIs this layer utilizes.
In the past, I have used NSURLConnection and NSOperation on a separate RunLoop. This seems overkill. I've seen libraries that subclass NSURLConnection. Others have a singleton Engine object that manages all requests.
The Engine and/or NSURLConnection seem best to me. But I am asking for input before I go too far down one road. My goals would be:
Ability to cancel a request
Concurrent requests
Non-blocking
Data object of current open requests
Any direction or existing references with code samples would be greatly appreciated.
I'm not sure about a "data object of current open requests", but ASIHTTPRequest does the first three and is very easy to use.
Update
Actually, it looks like ASINetworkQueue may fulfill your last bullet point.
I personally use a singleton engine with my large Apps though it might not always be the best case. All the URL's I use require signing in first, figured it would be best if one Class handles all of the requests to prevent multiple URLS from signing into the one location.
I basically create a protocol for all my different connection classes into my singleton and pass the delegate of both the calling class and the singleton into it. If an error occurs its passed to the singleton so it can deal with it, if it completes it returns the data to the calling class.

Delegation in a NSThreaded Design? (iPhone)

Im using a large amount of very small web services in my app and I have been down a couple of roads that does not scale or work as desired.
The Design approach Im thinking about:
The task for the viewController is to ask for a set of data from a general webServicesClass, this task is started in a new NSThread -> this will instantiate an object which solely retrieves the xml and returns it to the webServicesClass -> the webServicesClass now instantiates an object which solely can Parse some XML coming from this particular web service. The Parser then returns a nice Entity object to the webServiceClass. The WebserviceClass now needs to inform the viewController about this data.
The viewController implements a webServiceClassDelegate and some delegate methods to see if the web service request went as planned. e.g. -(void)aWebserviceFailed and -(void)aWebserviceSuccess.
0.5 Since the WebserviceClass is running is a different NSThread, will it be a problem calling delegate methods on the main NSThread in the parent object?
1.0 I think this design is sound as it completely incapsulates the retrieval, parsing and returning of the Entity in different classes. But, I will have to write delegation methods and implement delegation protocols on each step of the way, for each different webservice. i.e. starting from the bottom, the WebserviceClass must implement delegation methods for both the object that retrieves the XML (start, fail, success), then for the object that parses the XML(start, fail, success) and the WebserviceClass must be able to delegate each of these responses to the viewController that again must implement delegation methods from the WebserviceClass(start, fail, success).
Is there a much simpler way to do this?
I have some design pattern experience, but not from languages that uses delegation so consistently as Objective C. In AS3 or Java I would have events that could bubble up through the objects and inform whoever was listening about changes. In all the Objective example code I have read I have only seen NSNotifications (which would be the equivalent of the AS3 or Java 'Event') used 0.1% of the times.
The Design I described will give me something that scales perfectly for many web services and gives me complete control over where a potential error/exception happens, but it seems to be a lot of code to obtain this loose coupling.
1.1 Or should I fully embrace the delegation approach and get to work:)
Thanks for any pointers or help given. Im not asking for source code or the likes, more a "this is considered best practice in Objective C in the every day situation you just described" :)
I'd recommend taking a look at ASIHttpRequest(obtainable here) and NSOperation + NSOperationQueue (docs here). I don't think you should run a long-lived thread to talk to your web service all the time, unless you absolutely need a constant connection.
Basically ASIHttpRequest and NSOperation both encapsulate all of the networking and threading stuff. Operations make multi-threading on the iPhone really nice. Essentially you create an operation (through a factory or whatnot for ease of use), pop it in a queue and do something with the result.
As for what you do with the result (this applies to your original scenario too and 0.5 and 1.1) what typically happens is your operation/thread will then call a didSucceedAtGettingWhatever or didFailWithError:(NSError*) method. Delegation is pretty much the defacto way of making requests on the phone. If there are multiple delegates, then you can just use subject-observer, like you would in Java.
As for 1.0, ultimately no. What we typically do is we have an OperationDelegate and OperationTypes. Based upon which OperationType succeeded or completed, we have different logic. It's not the greatest and there are a ton of different ways of doing this, but you will have to have separate logic for separate events regardless of what you do. Whether or not that's in one method or many methods is up to you.

iphone RESTful webservices

Not even sure if the title is correct, however, what I'm trying to do is use the standard NSURLConnection class to handle responses from calling my webservice. I am using the POST method to update a database and the GET method to retrieve rows from the database. The problem I have is that these 2 actions may occur simultaneously so that the methods to handle the request may step on each other. In other words in my "connection didReceiveData" method I have 2 paths through the code depending on whether I'm handling a response from a GET or POST request.
I keep track on which request in being processed by an instance variable called requestType. The problem is that since the requests are being executed simultaneously the instance variable is being changed from GET to POST before the GET completes (or vice-versa). My question is how do I maintain 2 separate requests in this scenario? Do I synchronize the requests? Is there a way for threads to work here? Do I create 2 separate objects for each of the requests and have the logic in "didRecieveData" query for which object is being processed? Any help would be much appreciated!!
Dealt with a similar issue in one of our apps. The solution involved creating a class that represents a webservice call, responsible for calling its own url, loading its own data, etc. The call class had a delegate that would handle parsing the responses (in our case, a web service controller). Wound up getting rather complicated, but prevented the issue of NSURLConnections stepping on each other.
Seems like you've created a messy problem by having a class that tries to do too many things. I would suggest taking one of the following three approaches:
1) Write two classes, one for updates and one for retrievals. Each class creates it's own private NSURLConnection object and acts as the delegate for the async notifications received from the NSURLConnection. The classes could possible share some utility parsing code or extend a base object that has that parsing code in it. But the key being that the code calling these classes would instantiate one of them, make the call, and then release it. This will keep your code cleaner and will insure that the event notifications don't get intermingled.
2) Create a single class that, depending on initialization, does either a post or a get with it's own private instance of NSURLConnection. When a call needs to be made, instantiate the class, get the results, and then release the class.
3) Write your connection handling classes so they use the synchronous NSURLConnection method and call that call that class in a background thread.
Either way, clean code and clear object orientation will prevent messy scenarios like the one you're describing.
Create separate objects that handle the calls. If you want to issue multiple requests at once I would strongly recommend looking at NSOperationQueue, and making these objects subclasses of NSOperation... much nicer way to deal with multiple background requests.
A good example is here:
http://www.cimgf.com/2008/02/16/cocoa-tutorial-nsoperation-and-nsoperationqueue/
The idea there is that you use the non-asyncronous web calls, in operations that are run on separate threads. You can still use asynch calls in NSOperation as well, but doing so is a little trickier and for simple calls you probably do not need to.