The challenge is that the API's force you into developing in a completely asynchronous way with no real easy way for doing similar in a synchronous way. I think someone coming into this new (like me) is in the mindset of testing device/REST APIs using curl and trying to emulate that in Apple API's ... and thinking "all I need to do is request a URL and the API is requiring multiple object creation using call backs / blocks in a completely round about way, why can't I get what I need in 1 simple call?. Using NSURLSession, there is no way to simply submit a URL request and expect a synchronous reply with the data you want.
If your device/REST API is very simplistic, you might look and see if NSData dataWithContentsOfURL: does what you need. It's a synchronous call but I have't tested it to see how well it tolerates username/password and query string. NSData returns an object filled with the return data, you will need to figure out what that data means and parse it.
In my project I roughy did the following:
- create NSURLSessionConfguration object and added in desired headers
- create the NSURLSession with configuration object
- create NSMutableURLRequest object so I could change http request type, timeout, etc.
- I use NSURLSession dataTaskWithRequest: completionHandler: to set up the task. The handler block is very basic, all it does is copy the return data into instance variables, so something like this:
// Instance variables:
__block NSData * blockData;
__block NSURLResponse * blockResponse;
__block NSError * blockError;
// Callback
callback = ^(NSData *d, NSURLResponse *r, NSError *e) {
blockData = [d copy];
blockResponse = [r copy];
blockError = [e copy];
};
- [task resume] call to start the query
- Then I do the following which I am sure will make the API developers howl in rage:
while([task state] == NSURLSessionTaskStateRunning ) { [NSThread sleepForTimeInterval:.2]; }
This basically is a spin-lock on the task request and relies on the NSMutableURLRequest timeout to cancel and return error if the expected call takes too long. For my device I expect a response within about 5s and if it is longer, there's likely a problem.
I already know this is the wrong way to do things, but for my simple project it got me some tangible results while I continue to learn how to do these things more asychronously and/or use delegates to handle requests.
I hope that helps