Amit Hagin
Amit Hagin

Reputation: 3236

objective c - asynchronous http request blocks the program

I'm having a very strange problem with asynchronous http request:

I send a request to the server, which delays it by 10 seconds and then sends a response.

In order to not block the program, I do it asynchronously. if I just call the method (through NSThread) - it doesn't work. I assume it's because the thread dies before it finishes (the server waits 10 seconds). if I call the method and use CFRunLoopRun() - it actually works, but then the whole program stops working for 10 seconds. my question is how can I make the thread live enough time and still not block the program run. of course, there is an option that I have some mistake in my code that causes all that, so I publish all the relevant parts of it.

this is the main thread:

self.MessagesList=[[MessagesArray alloc] init];
[NSThread detachNewThreadSelector:@selector(backgroundMethod) toTarget:self withObject:nil];

-(void)backgroundMethod
{       
    [self.MessagesList updateFromServer];  
      CFRunLoopRun();        //the method dies without this line  
}

and this is the request:

-(void)updateFromServer{
    NSLog(@"method called");
    responseData = [NSMutableData data];
    NSURLRequest *request =
    [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:8000/messages/views/new_messages/"]];
    NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request     delegate:self];
    if(!connection) {
        NSLog(@"connection failed :(");
    } else {
        NSLog(@"connection succeeded  :)"); 
    }
}

while responseData is defined as the following:

@property (nonatomic,strong) NSMutableData *responseData;

I also tried performSelectorInBackground instead of NSThread, and even calling updateFromServer without any of them, and the results were the same.

I'm working with ARC - maybe it has something to do with that?

I really have to solve it, and don't know how, so I'll be glad if you help me.

thanks

Upvotes: 2

Views: 870

Answers (1)

gnasher729
gnasher729

Reputation: 52530

There's no need to use any threads with an asynchronous request. Just make sure you have a delegate with all the required delegate methods.

Calling the runloop is dangerous - if you are asking questions here instead of answering, don't call CFRunLoopRun ().

I don't see any code that actually starts the connection - nothing is going to happen with your code. It never starts sending anything to the server or receiving anything from the server.

ARC has nothing to do with this. ARC is not something that mysteriously stops http connections from working.

Upvotes: 1

Related Questions