NSURLConnection委托方法不执行

时间:2010-08-06 04:46:06

标签: iphone objective-c ios4

我正在运行Apple的以下示例代码 -

        NSString *requestURL = [[NSString alloc] initWithString:@"http://google.com/"];         
        NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:requestURL] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
        NSURLConnection *theConnection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self];

        if(theConnection) {

            NSLog(@"The connection has started...");

        } else {

            NSLog(@"Connection has failed...");

        }

但是下面的委托方法没有被调用。有人可以帮帮我吗?

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

2 个答案:

答案 0 :(得分:3)

如果您在后台线程上执行此操作,则可以在调用委托之前退出该线程。在调用触发后台线程CFRunLoopRun()的方法之后,调用刚启动传输的方法。然后在您的回调connectionDidFinishLoading:connection:didFailWithError:中确保您也运行:

CFRunLoopStop(CFRunLoopGetCurrent());

在这些方法结束时,否则你永远不会回来。

答案 1 :(得分:1)

您是否正在设置代理人?在该代码所在的类接口中,添加<NSURLConnectionDelegate>

例如:

@interface myClass : parentClass<NSURLConnectionDelegate>
祝你好运!

相关问题