I have a program that calls a web service post to update information but in the case of a DNS resolution failure, the app just waits for about 30 seconds for the error to come back before it continues normal execution.
NOTE: If the web service post fails, the application can still run fine, so I don’t want to wait for the response. Just post and move on, having the error come back whenever it does.
Below is the send method that comes back with error 410.
// Sends the request via HTTP.
-(void)send {
// 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:@"SoapRequest" 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:@"SoapRequest" 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);
}
}
// Create the connection
conn = [[NSURLConnection alloc] initWithRequest: request delegate: self];
if(conn) {
receivedData = [[NSMutableData data] retain];
} 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];
}
}
}
Any suggestions would be greatly appreciated!
Thanks in advance. 🙂
You might want to add some returns. I believe that if host is unreachable, you don’t want to proceed with the connection attempt.
Also, if one of your operations is blocking the thread, you might want to run your whole send method in a background queue.