2010-08-06 30 views
3

NSURLConnection的委托方法我是从苹果公司运行下面的示例代码 -不执行

 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 { 

回答

3

如果您在后台线程上执行此操作,则可能会在代理可以调用​​之前退出线程。在你调用后台线程CFRunLoopRun()的方法之后,调用刚开始传输的方法。然后在你的回调connectionDidFinishLoading:connection:didFailWithError:确保你也跑:

CFRunLoopStop(CFRunLoopGetCurrent()); 

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

1

你在设置代表吗?在类接口,其中的代码的位置,添加<NSURLConnectionDelegate>

例如:

@interface myClass : parentClass<NSURLConnectionDelegate> 

祝你好运!