不会调用NSURLConnection委托方法

时间:2012-08-21 10:51:54

标签: iphone objective-c ios macos asynchronous

我遇到了这个问题,我在堆栈溢出和其他地方经历了这么多帖子,无法找到解决方案。我也在主线程上运行它。代码如下。

@interface JsonViewController : UIViewController <UIActionSheetDelegate,UIWebViewDelegate,NSURLConnectionDelegate>
{
  ....
}
@implementation JsonViewController
- (void)viewDidLoad
{
    [super viewDidLoad];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://google.com"] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:60];
    rssFeedDetailViewConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
    NSLog(@"PRINTING RSS FEED %@", rssFeedDetailViewConnection);
[rssFeedDetailViewConnection scheduleInRunLoop:[NSRunLoop mainRunLoop] 
                                       forMode:NSDefaultRunLoopMode];
    [rssFeedDetailViewConnection start];
}


- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
NSLog(@"Hello");
responseData = [[NSMutableData alloc] init];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
     NSLog(@"Hello");
    [responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
     NSLog(@"Hello");
    [responseData release];
    [connection release];
// Show error message
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
 NSLog(@"Hello");
    // Use responseData
    [responseData release];
    [connection release];
 }

非常感谢任何帮助。我已经坚持了两天了。

2 个答案:

答案 0 :(得分:1)

您不需要这些陈述:

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

因为您正在使用initWithRequest:delegate:。此调用已开始加载数据。

如果删除这些特定陈述会怎样?

有关NSURLConnection的更多信息。

答案 1 :(得分:0)

有一个名为finished的布尔值,并在您编写NSURLConnection代码的地方添加此代码。

 while(!finished) {
    [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
}

并在您的connectionDidFinishLoading中添加此

 finished = TRUE; 

这是有效的。它不是我理解的最佳解决方案,但它有效。