Usi Usi
Usi Usi

Reputation: 2997

NSURLConnection Bug when I run It in background.... how can I fix?

I've this code but I can't understand why I must run this on the main thread. If I run this in the background It doesn't do the post request. Is it a bug? How can I solve this problem?

- (void)setRead:(MWFeedItem *)entry
{    [self getToken:YES];

    NSString *url=[NSString stringWithFormat:@"https://www.google.com/reader/api/0/edit-tag?a=user/-/state/com.google/read&i=%@&T=%@", entry.identifier, token];

    [self postRequestWithURLState:url];

}
- (void)postRequestWithURLState:(NSString *)url
{
    NSString *bodyRequest = nil;
    NSURL *requestURL = [NSURL URLWithString:url];
    NSMutableURLRequest *theRequest = [[NSMutableURLRequest alloc] init];

    //NSLog(@"-------------- bodyRequest: %@", bodyRequest);



    [theRequest setURL:requestURL];
    [theRequest setTimeoutInterval:0.5];
    [theRequest setHTTPMethod:@"POST"];
    [theRequest setHTTPBody:[bodyRequest dataUsingEncoding:NSASCIIStringEncoding]];
    [self.oauthAuthentication authorizeRequest:theRequest];
    [NSURLConnection connectionWithRequest:theRequest delegate:self];

    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;



}

this is my call:

-(void)segnaLettura:(MWFeedItem *)item{

        [reader setRead:item];

}
- (void) segnaread:(MWFeedItem *)item{
    [self performSelectorOnMainThread:@selector(segnaLettura:) withObject:item waitUntilDone:NO];
}

Upvotes: 0

Views: 754

Answers (1)

Rob Napier
Rob Napier

Reputation: 299623

In order for an asynchronous NSURLConnection to function, it requires the thread's runloop to be processed. While new threads automatically get a runloop, it is up to you to run it.

You can learn how to do this in the Threading Programming Guide, and I can explain it more, but most of the time this isn't what you want. Most of the time in iOS, background threads should be managed with NSOperation or GCD. Generally, if you're manually spawning a thread on iOS 4+, you're doing it wrong. There are exceptions, but not often.

The first question here should be "why do I even have a background thread for this?"

If you really need a background thread, then the way you're doing segnaread is probably fine.

Upvotes: 1

Related Questions