NSURLConnection doesn't call delegate methods

2019-01-23 04:27发布

问题:

I saw similar questions here, but I couldn't find solution to my problem. I have a simple NSURLConnection in main thread (At least I didn't create any other threads), but my delegate methods aren't get called

[[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];

and no methods called, e.g.

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"didReceiveResponse");
}

self is also a delegate for NSXMLParser, but I think it should not be a problem, as I have this working in my other class in the same project. I checked everything 10 times already, but can't find any problem.

I've seen some hack to solve it here: http://www.depl0y.com/?p=345 but I don't like it, May be someone knows better solution? thanks

回答1:

The only reason I know is a separate thread (that is already terminated when the delegate methods are called).

Try to NSLog(@"Is%@ main thread", ([NSThread isMainThread] ? @"" : @" NOT"));right before the url connection creation



回答2:

Try running your connection on main thread:

NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest:request
                                         delegate:self startImmediately:NO];

[connection scheduleInRunLoop:[NSRunLoop mainRunLoop] 
            forMode:NSDefaultRunLoopMode];
[connection start];


回答3:

The autorelease is dangerous. The calls to the delegate are made after your function returns (asynchronously). Are you retaining it somewhere else?



回答4:

You have to release the NSURLConnection object in the - (void)connectionDidFinishLoading:(NSURLConnection *)connection callback as pointed out in the Apple documentation, not elsewhere:

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
  // Do whatever you want here

  // Release the connection
  [connection release];
}

Don't release it with autorelease, as Lou Franco suggested.

If it is not the problem, then maybe you have to implement all the required methods in the delegate class:

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error

- (void)connectionDidFinishLoading:(NSURLConnection *)connection

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response

The delegate is retained by NSURLConnection so you don't have to worry about it.



回答5:

I think you may have missed NSURLConnectionDelegate in your class header file.

For example:

@interface yourClass : NSObject <NSURLConnectionDelegate>