简体   繁体   English

NSURLConnection委托方法没有被调用

[英]NSURLConnection Delegate methods are not getting called

I have had this problem and i went through so many posts here on stack overflow and everywhere else and couldnt find a solution. 我遇到了这个问题,在堆栈溢出和其他所有地方,我经历了很多帖子,找不到解决方案。 Im running it on the main thread as well. 我也在主线程上运行它。 Code as follows. 代码如下。

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

Any help would be greatly appreciated. 任何帮助将不胜感激。 Ive been stuck with this for two days now.. 我已经坚持了两天了。

You don't need these statements: 您不需要以下语句:

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

since you're using initWithRequest:delegate: . 由于您使用的是initWithRequest:delegate: This call already starts loading the data. 该调用已经开始加载数据。

What happens if you remove these particular statements? 如果删除这些特定语句会怎样?

More info on the NSURLConnection . 有关NSURLConnection的更多信息。

Have a boolean called finished and add this code where ever you have written your NSURLConnection Code. 将一个布尔值称为finish,并在编写NSURLConnection代码的任何位置添加此代码。

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

and in your connectionDidFinishLoading just add this 并在您的connectionDidFinishLoading中添加此内容

 finished = TRUE; 

and that works. 那行得通。 Its not the best solution i understand but it works. 它不是我理解的最佳解决方案,但它可以工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM