NSURLConnection doesn't call delegate methods

被刻印的时光 ゝ 提交于 2019-11-28 23:23:52
Michael Kessler

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

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];

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

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.

Terence

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

For example:

@interface yourClass : NSObject <NSURLConnectionDelegate>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!