I'm having an issue with an objective-C uploader class that will not upload (fail / success delegate not called and the server shows no incoming request) unless I have a spin loop. It works perfectly with a spin loop.
I'm new to objective-C, The setup is as follows: Main app instantiates a C++ class (cppClass) that runs a static function (cppFuncA) in a separate pThread.
Static function (cppFuncA) instantiates an objective-C class/object (UploadFunc) which takes some data and uploads it.
CppClass {
static void cppFuncA (...);
}
cppFuncA(...) {
UploadFunc* uploader = [[[UploadFunc alloc] retain] init];
while (condition) {
...
[uploader uploadData:(NSData*)data];
}
[uploader release]
}
Uploader.h
@interface UploadFunc : NSObject
{
bool conditional;
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error;
- (void)connectionDidFinishLoading:(NSURLConnection *)connection;
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response;
- (void) uploadData:(NSData*)data;
@end
Uploader.mm
@implementation UploadFeedback
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
conditional = false;
[connection release];
NSLog(@"Connection failed! Error - %@ %@",
[error localizedDescription],
[[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
conditional = false;
NSLog(@"Succeeded! Received %d bytes of data",0);
[connection release];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"Response=%@", response);
}
-(void) uploadData:(NSData*)data
{
…
NSMutableURLRequest *theRequest=[NSMutableURLRequest requestWithURL:theURL];
… construct request …
NSURLConnection* theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
// Only works if I have this following spin loop
conditional = true;
while(conditional) {
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}
if (!theConnection) std::cerr << "Connection to feedback failed\n";
}
The last function "-(void) uploadData:(NSData*)data" is where I am having my issue. It will not work without the spin loop. Any ideas on what is going on?
I added retain to the NSURLRequest and NSURLConnection so I do not think its a race condition where the request is not being copied.
EDIT: I feel like these might be a similar issues: NSURLConnection - how to wait for completion and Asynchronous request to the server from background thread however my object (UploadFunc) still exists even after the function finishes and goes out of scope...