2010-08-06 44 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> 

祝你好運!