Use observer to signal semaphore? - ios

I use the following method to attempt to synchronously obtain an OAuth access token within 10 seconds, otherwise return nil. It works fine, however as an exercise I would like to convert my code to use a semaphore.
The Runloop version
- (NSString*)oAuthAccessToken
{
#synchronized (self)
{
NSString* token = nil;
_authenticationError = nil;
if (_authentication.accessToken)
{
token = [NSString stringWithFormat:#"Bearer %#", _authentication.accessToken];
}
else
{
[GTMOAuth2ViewControllerTouch authorizeFromKeychainForName:_keychainName authentication:_authentication];
[_authentication authorizeRequest:nil delegate:self didFinishSelector:#selector(authentication:request:finishedWithError:)];
for (int i = 0; i < 5; i++)
{
[[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1]];
if (_authentication.accessToken)
{
token = [NSString stringWithFormat:#"Bearer %#", _authentication.accessToken];
break;
}
else if (_authenticationError)
{
break;
}
}
}
// LogDebug(#"Returning token: %#", token);
return token;
}
}
Semaphore Version
The semaphore version of the code goes a little something like this:
- (NSString*)oAuthAccessToken
{
#synchronized (self)
{
NSString* token = nil;
_authenticationError = nil;
if (_authentication.accessToken)
{
token = [NSString stringWithFormat:#"Bearer %#", _authentication.accessToken];
}
else
{
_authorizationSemaphore = dispatch_semaphore_create(0);
dispatch_async(_authorizationRequestQueue, ^(void)
{
[GTMOAuth2ViewControllerTouch authorizeFromKeychainForName:_keychainName authentication:_authentication];
[_authentication authorizeRequest:nil delegate:self didFinishSelector:#selector(authentication:request:finishedWithError:)];
});
dispatch_semaphore_wait(_authorizationSemaphore, DISPATCH_TIME_FOREVER);
if (_authentication.accessToken)
{
token = [NSString stringWithFormat:#"Bearer %#", _authentication.accessToken];
}
}
return token;
}
}
Gotcha!!! GTMOAuth2 sometimes returns immediately
When GTMOAuth2 needs to hit the network it calls back via a delegate method. In this method I signal my semaphore.
Sometimes GTMOAuth2 is able to return immediately. The problem is the method returns void.
How can I signal my semaphore in the latter case? If I add an observer to the authentication.assessToken will it be fired?

I'm not familiar with the GTMOAuth2 library but authentication.accessToken is a property, so and there doesn't seem to be anything that prevents it from being KVO compliant. Adding an observer should work for you in all cases, both for the async and the sync. Therefore, I'd consider only the async case.
If you want to make your solution even cleaner, then you should definitely try Reactive Cocoa.

Related

return internal value function in a external function

I have this code:
- (NSString *) login {
datos=#"";
NSString __block *variable;
NSString *sqlQueryExisteUsuario;
sqlQueryExisteUsuario = [[NSString alloc] initWithFormat:#"SELECT COUNT(*) FROM tableName WHERE field='value' AND field='value'"];
SQLClient* client = [SQLClient sharedInstance];
client.delegate = self;
[client connect:#"serverName" username:#"username" password:#"password" database:#"database" completion:^(BOOL success) {
[client execute:sqlQueryExisteUsuario completion:^(NSArray* results) {
variable = [self processLogin:results];
NSLog(#"In: %#",variable);
[client disconnect];
}];
}];
NSLog(#"Out: %#",variable);
return nil;
}
- (NSString *)processLogin:(NSArray*)data
{
existeArray = [NSMutableArray array];
for (NSArray* table in data)
for (NSDictionary* row in table)
for (NSString* column in row)
[existeArray addObject:row[column]];
NSString *existe=existeArray[0];
if([existe isEqualToString:#"1"])
{
datos=#"yes";
}else{
datos=#"no";
}
return datos;
}
In the first call to NSLog, which begins with In, the value shows. In the second call, which begins with Out, the value doesn't show. Why?
Your connect is async method, so NSLog... line will be executed earlier than completion block. So, you have to use blocks also:
- (NSString *) loginWithCompletion:(void(^)(NSString *result))handler
{
datos=#"";
NSString *sqlQueryExisteUsuario;
sqlQueryExisteUsuario = [[NSString alloc] initWithFormat:#"SELECT COUNT(*) FROM tableName WHERE field='value' AND field='value'"];
SQLClient* client = [SQLClient sharedInstance];
client.delegate = self;
[client connect:#"serverName" username:#"username" password:#"password" database:#"database" completion:^(BOOL success) {
if (success) {
[client execute:sqlQueryExisteUsuario completion:^(NSArray* results) {
NSString *variable = [self processLogin:results];
NSLog(#"In: %#",variable);
[client disconnect];
if (handler) {
handler (variable);
}
}];
} else {
//TODO: handle this
if (handler) {
handler (nil);
}
}
}];
}
Usage:
- (void)ff
{
[self loginWithCompletion:^(NSString *variable) {
//Do something with variable
}];
}
The problem is that your variable is being set inside a completion block: the variable variable (not a great name, BTW!) is set inside not only one but two blocks - that's the "completion" part of your code – both of which are best thought of a bit(!) like a miniature anonymous function: in this case, they get run when the system is ready for it, not straight away.
iOS will start execution of your connect code, then jump ahead to NSLog(#"Out: %#",variable), then execute the completion block of connect, which in turn starts more code (execute), which has its own completion block, which finally gets executed. As #rmaddy says in a comment below, the technical name for this is asynchronous code: the bit inside your block does not get executed immediately, which allows the system to continue doing other things while waiting for your task to complete.
So the running order will be:
1) You declare variable.
2) Your connection code starts.
3) variable gets printed out.
4) The connection completes.
5) Your execute code starts.
6) Your execute code completes.
7) variable gets set to the final value.

Objective c- How to make sure block executes before executing any other code further?

Overview : I am using Amazon DynamoDB for my login service. And my login method looks like this in some UserAccount.m. And I am calling this class method in some LoginViewController.m on login button tap:
+ (BOOL)loginWithUsername:(NSString *)username password:(NSString *)password{
AWSDynamoDBObjectMapper *dynamoDBObjectMapper = [AWSDynamoDBObjectMapper defaultDynamoDBObjectMapper];
BOOL __block isLoginSuccessful = NO;
[[dynamoDBObjectMapper load:[User class] hashKey:username rangeKey:#"key"]
continueWithBlock:^id(AWSTask *task) {
if (task.error) {
NSLog(#"The request failed. Error: [%#]", task.error);
}
if (task.exception) {
NSLog(#"The request failed. Exception: [%#]", task.exception);
}
if (task.result) {
//Do something with the result.
User *user = task.result; // User is a model I'm using
NSLog(#"pass: %#", user.password);
// Check returned password from DynamoDB with user-supplied password.
if ([user.password isEqualToString:password]) {
isLoginSuccessful = YES;
}
}
return nil;
}];
return isLoginSuccessful; // <-- Issue: function returns before block executes and isLoginSuccessful value is changed.
}
The issue is function returns before block executes. What I tried:
i) I read up about using dispatch groups on this SO question
ii) Tried to execute method - (AWSTask *)load:(Class)resultClass hashKey:(id)hashKey rangeKey:(id)rangeKey on main thread like this but still function returns before block execution finishes.:
dispatch_async(dispatch_get_main_queue(), ^{
[[dynamoDBObjectMapper load:[User class]
hashKey:username
rangeKey:#"key"] continueWithExecutor:[AWSExecutor mainThreadExecutor] withBlock:^id(AWSTask *task) {
if (!task.error) {
User *user = task.result;
NSLog(#"pass: %#", user.password);
//Do something with the result.
if ([user.password isEqualToString:password]) {
isLoginSuccessful = YES;
}
} else {
NSLog(#"Error: [%#]", task.error);
}
return nil;
}];
});
Am I missing out something here/ doing wrong in my approach? Any suggestion towards right direction would be really helpful. Thank you!
Edit 1: Including function from where loginWithUsername class method is being called:
#IBAction func login(sender: AnyObject) {
if(UserAccount.loginWithUsername(txtEmail.text, password: txtPassword.text)){
println("SUCCESS")
lblIncorrect.hidden = true
}
else{
println("Incorrect username/password")
lblIncorrect.hidden = false
}
}
It is the basic idea of GCD that blocks are executed "in background", so the control flow can return to the sender of the message before the task is finished. This is, because the task is a potential long runner and you do not want to block the sending control flow, esp. if it is the main thread.
If you want to execute code after finishing the operation, simply add it to the block. This is the code inside login(): Add the if to the block and remove the block variable and the return value. Make the method void.
To have a general pattern:
-(IBAction)doSomething:(id)sender
{
[self executeOperation]; // Method becomes void
// Remove code processing on result
}
-(void)executeOperation // Method becomes void
{
[receiver longRunnerWithBlock:^(id result)
{
…
// Add code processing on result
}
}
Please take care, that the block is potentially run on a different thread than the main thread, so you have to dispatch it on the main thread, if it is UI related.
OR you could just take a page from Googles iOS framework code and do it the easy way like this:
- (void)runSigninThenInvokeSelector:(SEL)signInDoneSel {
if (signInDoneSel) {
[self performSelector:signInDoneSel];
}
}

Testing asynchronous call in unit test in iOS

I am facing a problem while unit testing an asynchronous call in iOS. (Although it is working fine in view controllers.)
Has anyone faced this issue before? I have tried using a wait function but I'm still facing the same problem.
Please suggest an example of a good way to do this.
You'll need to spin the runloop until your callback is invoked. Make sure that it gets invoked on the main queue, though.
Try this:
__block BOOL done = NO;
doSomethingAsynchronouslyWithBlock(^{
done = YES;
});
while(!done) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
You can also use a semaphore (example below), but I prefer to spin the runloop to allow asynchronous blocks dispatched to the main queue to be processed.
dispatch_semaphore_t sem = dispatch_semaphore_create(0);
doSomethingAsynchronouslyWithBlock(^{
//...
dispatch_semaphore_signal(sem);
});
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER);
Here is Apple's description of native support for async testing.
TL;DR manual:
Look at XCTextCase+AsynchronousTesting.h
There is special class XCTestExpectation with only one public method: - (void)fulfill;
You should init instance of this class and in success case call fulfill method. Otherwise your test will fail after timeout that you specify in that method:
- (void)waitForExpectationsWithTimeout:(NSTimeInterval)timeout handler:(XCWaitCompletionHandler)handlerOrNil;
Example:
- (void)testAsyncMethod
{
//Expectation
XCTestExpectation *expectation = [self expectationWithDescription:#"Testing Async Method Works Correctly!"];
[MyClass asyncMethodWithCompletionBlock:^(NSError *error) {
if(error)
NSLog(#"error is: %#", error);
else
[expectation fulfill];
}];
//Wait 1 second for fulfill method called, otherwise fail:
[self waitForExpectationsWithTimeout:1 handler:^(NSError *error) {
if(error)
{
XCTFail(#"Expectation Failed with error: %#", error);
}
}];
}
I think many of the suggested solutions in this post has the problem that if the asynchronous operation does not complete the "done" flag is never set, and the test will hang forever.
I have successfully used this approach in many of my test.
- (void)testSomething {
__block BOOL done = NO;
[obj asyncMethodUnderTestWithCompletionBlock:^{
done = YES;
}];
XCTAssertTrue([self waitFor:&done timeout:2],
#"Timed out waiting for response asynch method completion");
}
- (BOOL)waitFor:(BOOL *)flag timeout:(NSTimeInterval)timeoutSecs {
NSDate *timeoutDate = [NSDate dateWithTimeIntervalSinceNow:timeoutSecs];
do {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:timeoutDate];
if ([timeoutDate timeIntervalSinceNow] < 0.0) {
break;
}
}
while (!*flag);
return *flag;
}
Since Xcode 6 this built in to XCTest as a category:
See https://stackoverflow.com/a/24705283/88164
Here's another alternative, XCAsyncTestCase, that works well with OCMock if you need to use it. It's based on GHUnit's async tester, but is uses the regular XCTest framework instead.
Fully compatible with Xcode Bots.
https://github.com/iheartradio/xctest-additions
Usage is the same, just import and subclass XCAsyncTestCase.
#implementation TestAsync
- (void)testBlockSample
{
[self prepare];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(){
sleep(1.0);
[self notify:kXCTUnitWaitStatusSuccess];
});
// Will wait for 2 seconds before expecting the test to have status success
// Potential statuses are:
// kXCTUnitWaitStatusUnknown, initial status
// kXCTUnitWaitStatusSuccess, indicates a successful callback
// kXCTUnitWaitStatusFailure, indicates a failed callback, e.g login operation failed
// kXCTUnitWaitStatusCancelled, indicates the operation was cancelled
[self waitForStatus:kXCTUnitWaitStatusSuccess timeout:2.0];
}
AGAsyncTestHelper is a C macro for writing unit tests with asynchronous operations and works with both SenTestingKit and XCTest.
Simple and to the point
- (void)testAsyncBlockCallback
{
__block BOOL jobDone = NO;
[Manager doSomeOperationOnDone:^(id data) {
jobDone = YES;
}];
WAIT_WHILE(!jobDone, 2.0);
}
Sam Brodkin already gave the right answer.
Just to make the answer looks better at first sight, I bring the sample code here.
Use XCTestExpectation.
// Test that the document is opened. Because opening is asynchronous,
// use XCTestCase's asynchronous APIs to wait until the document has
// finished opening.
- (void)testDocumentOpening
{
// Create an expectation object.
// This test only has one, but it's possible to wait on multiple expectations.
XCTestExpectation *documentOpenExpectation = [self expectationWithDescription:#"document open"];
NSURL *URL = [[NSBundle bundleForClass:[self class]]
URLForResource:#"TestDocument" withExtension:#"mydoc"];
UIDocument *doc = [[UIDocument alloc] initWithFileURL:URL];
[doc openWithCompletionHandler:^(BOOL success) {
XCTAssert(success);
// Possibly assert other things here about the document after it has opened...
// Fulfill the expectation-this will cause -waitForExpectation
// to invoke its completion handler and then return.
[documentOpenExpectation fulfill];
}];
// The test will pause here, running the run loop, until the timeout is hit
// or all expectations are fulfilled.
[self waitForExpectationsWithTimeout:1 handler:^(NSError *error) {
[doc closeWithCompletionHandler:nil];
}];
}
you can use async api calling in swift like this
private let serverCommunicationManager : ServerCommunicationManager = {
let instance = ServerCommunicationManager()
return instance
}()
var expectation:XCTestExpectation?
func testAsyncApiCall() {
expectation = self.expectation(description: "async request")
let header = ["Authorization":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6ImQ4MmY1MTcxNzI4YTA5MjI3NWIzYWI3OWNkOTZjMGExOTI4MmM2NDEyZjMyYWQzM2ZjMzY4NmU2MjlhOWY2YWY1NGE0MDI4MmZiNzY2NWQ3In0.eyJhdWQiOiIxIiwianRpIjoiZDgyZjUxNzE3MjhhMDkyMjc1YjNhYjc5Y2Q5NmMwYTE5MjgyYzY0MTJmMzJhZDMzZmMzNjg2ZTYyOWE5ZjZhZjU0YTQwMjgyZmI3NjY1ZDciLCJpYXQiOjE1MDg4MjU1NTEsIm5iZiI6MTUwODgyNTU1MSwiZXhwIjoxNTQwMzYxNTUxLCJzdWIiOiIiLCJzY29wZXMiOltdfQ.osoMQgiY7TY7fFrh5r9JRQLQ6AZhIuEbrIvghF0VH4wmkqRUE6oZWjE5l0jx1ZpXsaYUhci6EDngnSTqs1tZwFTQ3srWxdXns2R1hRWUFkAN0ri32W0apywY6BrahdtiVZa9LQloD1VRMT1_QUnljMXKsLX36gXUsNGU6Bov689-bCbugK6RC3n4LjFRqJ3zD9gvkRaODuOQkqsNlS50b5tLm8AD5aIB4jYv3WQ4-1L74xXU0ZyBTAsLs8LOwvLB_2B9Qdm8XMP118h7A_ddLo9Cyw-WqiCZzeZPNcCvjymNK8cfli5_LZBOyjZT06v8mMqg3zszWzP6jOxuL9H1JjBF7WrPpz23m7dhEwa0a-t3q05tc1RQRUb16W1WhbRJi1ufdMa29uyhX8w_f4fmWdAnBeHZ960kjCss98FA73o0JP5F0GVsHbyCMO-0GOHxow3-BqyPOsmcDrI4ay006fd-TJk52Gol0GteDgdntvTMIrMCdG2jw8rfosV6BgoJAeRbqvvCpJ4OTj6DwQnV-diKoaHdQ8vHKe-4X7hbYn_Bdfl52gMdteb3_ielcVXIaHmQ-Dw3E2LSVt_cSt4tAHy3OCd7WORDY8uek4Paw8Pof0OiuqQ0EB40xX5hlYqZ7P_tXpm-W-8ucrIIxgpZb0uh-wC3EzBGPjpPD2j9CDo"]
serverCommunicationManager.sendServerRequest(httpMethodType: .get, baseURL: "http://192.168.2.132:8000/api/v1/user-role-by-company-id/2", param: nil, header: header) { (isSuccess, msg , response) in
if isSuccess
{
let array = response as! NSArray
if array.count == 8
{
XCTAssertTrue(true)
self.expectation?.fulfill()
}
else
{
XCTAssertFalse(false)
XCTFail("array count fail")
}
}
}
waitForExpectations(timeout: 5) { (error) in
if let error = error{
XCTFail("waiting with error: \(error.localizedDescription)")
}
}
}
I suggest you should have a look on the tests of Facebook-ios-sdk. It's a good example of how to test async unit test on iOS, though personally I think async tests should be break into sync tests.
FBTestBlocker: a blocker that prevent current thread exits with specified timeout. You can drag and drop this to your project, but you need to remove OCMock related stuff if you don't have that in you project.
FBTestBlocker.h
FBTestBlocker.m
FBURLConnectionTests: test examples you should look at.
FBURLConnectionTests.h
FBURLConnectionTests.m
This code snippet should give you some idea
- (void)testExample
{
FBTestBlocker *_blocker = [[FBTestBlocker alloc] initWithExpectedSignalCount:1];
__block BOOL excuted = NO;
[testcase test:^(BOOL testResult) {
XCTAssert(testResult, #"Should be true");
excuted = YES;
[_blocker signal];
}];
[_blocker waitWithTimeout:4];
XCTAssertTrue(excuted, #"Not executed");
}
Try KIWI framework. It's powerful and might help you with other kinds of tests.
I recommend you connection semaphore + runloop, i also wrote method which take block:
// Set the flag to stop the loop
#define FLEND() dispatch_semaphore_signal(semaphore);
// Wait and loop until flag is set
#define FLWAIT() WAITWHILE(dispatch_semaphore_wait(semaphore, DISPATCH_TIME_NOW))
// Macro - Wait for condition to be NO/false in blocks and asynchronous calls
#define WAITWHILE(condition) \
do { \
while(condition) { \
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:1]]; \
} \
} while(0)
method:
typedef void(^FLTestAsynchronousBlock)(void(^completion)(void));
void FLTestAsynchronous(FLTestAsynchronousBlock block) {
FLSTART();
block(^{
FLEND();
});
FLWAIT();
};
and call
FLTestAsynchronous(^(void(^completion)()){
[networkManager signOutUser:^{
expect(networkManager.currentUser).to.beNil();
completion();
} errorBlock:^(NSError *error) {
expect(networkManager.currentUser).to.beNil();
completion();
}];
});
If you are using XCode 6, you can test async network calls like this:
XCTest and asynchronous testing in Xcode 6

Return parent method from within block

Hi I'm new to using blocks in Objective-C
What I think I want is the following:
- (void) iNeedAToken {
NSString *token = [self theMethodThatShouldReturnTheToken];
}
- (NSString) theMethodThatShouldReturnTheToken {
[myAwesomeAsyncMethod success:^(id JSON) {
NSString *token = [JSON objectForKey:#"FOO"];
return token;
}]
}
Is this possible? Or is this the wrong logic all together?
Thanks!
You're mixing async with synchronous code. You're theMethodThatShouldReturnTheToken already returned (you're missing a return value) before the block passed to success finishes.
Best bet would be to continue your process from the success block.
- (void) tokenRequestContext1
{
[self requestToken:^(NSString *token) {
// do something with token
}];
}
- (void) requestToken:(void(^)(NSString *))tokenBlock
{
[myAwesomeAsyncMethod success:^(id JSON) {
NSString *token = [JSON objectForKey:#"FOO"];
if (tokenBlock) {
tokenBlock(token);
}
}];
}
You start by calling requestToken. This will start the async request for your token. Some time might pass, but eventually doSomethingWithToken will be called where you can use the received token.
There is a description of way to wait until complition block will be finished: http://omegadelta.net/2011/05/10/how-to-wait-for-ios-methods-with-completion-blocks-to-finish/
Regular version of this code is:
- (void) iNeedAToken {
[self theMethodThatShouldReturnTheToken:^(id res){ token = res;}];
NSString *token = [self theMethodThatShouldReturnTheToken];
}
- (void) theMethodThatShouldReturnTheToken:(void (^)(id res)result) {
[myAwesomeAsyncMethod success:^(id JSON) {
NSString *token = [JSON objectForKey:#"FOO"];
result(token);
}]
}

NSURLConnection delegate methods on background thread

EDIT2 - Rewrote the question
I want to do some web service communication in the background. I am using Sudzc as the handler of HTTPRequests and it works like this:
SudzcWS *service = [[SudzcWS alloc] init];
[service sendOrders:self withXML:#"my xml here" action:#selector(handleOrderSending:)];
[service release];
It sends some XML to the webservice, and the response (in this one, a Boolean) is handled in the selector specified:
- (void)handleOrderSending:(id)value
{
//some controls
if ([value boolValue] == YES)
{
//my stuff
}
}
When I tried to use Grand Central Dispatch on my sendOrders:withXML:action: method, I noticed that the selector is not called. And I believe the reason for that is that NSURLConnection delegate messages are sent to the thread of which the connection is created But the thread does not live that long, it ends when the method finishes, killing any messages to the delegate.
Regards
EDIT1
[request send] method:
- (void) send {
//dispatch_async(backgroundQueue, ^(void){
// If we don't have a handler, create a default one
if(handler == nil) {
handler = [[SoapHandler alloc] init];
}
// Make sure the network is available
if([SoapReachability connectedToNetwork] == NO) {
NSError* error = [NSError errorWithDomain:#"SudzC" code:400 userInfo:[NSDictionary dictionaryWithObject:#"The network is not available" forKey:NSLocalizedDescriptionKey]];
[self handleError: error];
}
// Make sure we can reach the host
if([SoapReachability hostAvailable:url.host] == NO) {
NSError* error = [NSError errorWithDomain:#"SudzC" code:410 userInfo:[NSDictionary dictionaryWithObject:#"The host is not available" forKey:NSLocalizedDescriptionKey]];
[self handleError: error];
}
// Output the URL if logging is enabled
if(logging) {
NSLog(#"Loading: %#", url.absoluteString);
}
// Create the request
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL: url];
if(soapAction != nil) {
[request addValue: soapAction forHTTPHeaderField: #"SOAPAction"];
}
if(postData != nil) {
[request setHTTPMethod: #"POST"];
[request addValue: #"text/xml; charset=utf-8" forHTTPHeaderField: #"Content-Type"];
[request setHTTPBody: [postData dataUsingEncoding: NSUTF8StringEncoding]];
if(self.logging) {
NSLog(#"%#", postData);
}
}
//dispatch_async(dispatch_get_main_queue(), ^(void){
// Create the connection
conn = [[NSURLConnection alloc] initWithRequest: request delegate: self];
if(conn) {
NSLog(#" POST DATA %#", receivedData);
receivedData = [[NSMutableData data] retain];
NSLog(#" POST DATA %#", receivedData);
} else {
// We will want to call the onerror method selector here...
if(self.handler != nil) {
NSError* error = [NSError errorWithDomain:#"SoapRequest" code:404 userInfo: [NSDictionary dictionaryWithObjectsAndKeys: #"Could not create connection", NSLocalizedDescriptionKey,nil]];
[self handleError: error];
}
}
//});
//finished = NO;
// while(!finished) {
//
// [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
//
// }
//});
}
The parts that are commented out are the various things I tried. The last part worked but I'M not sure if that's a good way. In the NURLConnection delegate method of the class, here is what happens:
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
NSError* error;
if(self.logging == YES) {
NSString* response = [[NSString alloc] initWithData: self.receivedData encoding: NSUTF8StringEncoding];
NSLog(#"%#", response);
[response release];
}
CXMLDocument* doc = [[CXMLDocument alloc] initWithData: self.receivedData options: 0 error: &error];
if(doc == nil) {
[self handleError:error];
return;
}
id output = nil;
SoapFault* fault = [SoapFault faultWithXMLDocument: doc];
if([fault hasFault]) {
if(self.action == nil) {
[self handleFault: fault];
} else {
if(self.handler != nil && [self.handler respondsToSelector: self.action]) {
[self.handler performSelector: self.action withObject: fault];
} else {
NSLog(#"SOAP Fault: %#", fault);
}
}
} else {
CXMLNode* element = [[Soap getNode: [doc rootElement] withName: #"Body"] childAtIndex:0];
if(deserializeTo == nil) {
output = [Soap deserialize:element];
} else {
if([deserializeTo respondsToSelector: #selector(initWithNode:)]) {
element = [element childAtIndex:0];
output = [deserializeTo initWithNode: element];
} else {
NSString* value = [[[element childAtIndex:0] childAtIndex:0] stringValue];
output = [Soap convert: value toType: deserializeTo];
}
}
if(self.action == nil) { self.action = #selector(onload:); }
if(self.handler != nil && [self.handler respondsToSelector: self.action]) {
[self.handler performSelector: self.action withObject: output];
} else if(self.defaultHandler != nil && [self.defaultHandler respondsToSelector:#selector(onload:)]) {
[self.defaultHandler onload:output];
}
}
[self.handler release];
[doc release];
[conn release];
conn = nil;
[self.receivedData release];
}
The delegate is unable to send messages because the thread it is dies when -(void)send finishes.
The method definition for sendOrders suggests that it is already designed to execute requests in an asynchronous fashion. You should have a look into the implementation of sendOrders: withXML: action: to find out if this is the case.
Without seeing your implementation using GCD or the code from SudzcWS it's hard to say what's going wrong. Despite the preceding caveats, the following might be of use.
It looks like you may be releasing SudzcWS *service before it is completed.
The following:
SudzcWS *service = [[SudzcWS alloc] init];
dispatch_async(aQueue, ^{
[sevice sendOrders:self withXML:xml action:#selector(handleOrderSending:)];
}
[service release];
could fail unless SudzcWS retains itself. You dispatch your block asynchronously, it gets put in a queue, and execution of the method continues. service is released and gets deallocated before the block executes or while service is waiting for a response from the webserver.
Unless otherwise specified, calling a selector will execute that selector on the same thread it is called on. Doing something like:
SudzcWS *service = [[SudzcWS alloc] init];
dispatch_async(aQueue, ^{
[sevice sendOrders:self withXML:xml action:#selector(handleOrderSending:)];
}
- (void)handleOrderSending:(id)value
{
//some controls
//your stuff
[service release];
}
should ensure that both the sendOrders: method and the handleOrderSending: are executed on the queue aQueue and that service is not released until it has executed the selector.
This will require you to keep a pointer to service so that handleOrderSending: can release it. You might also want to consider simply hanging onto a single SudzcWS instance instead of creating and releasing one each time you want to use it, this should make your memory management much easier and will help keep your object graph tight.
I've had help from both these links SO NURLConnection question and the original one.
It does not seem risky for my code and I will use it at my own risk. Thanks.
Any recommendations are still welcome of course.
Additional thanks to Pingbat for taking the time to try and help.

Resources