没有使用NSURLConnection异步返回数据

Lea*_*chy 7 iphone cocoa-touch asynchronous objective-c nsurlconnection

我有点时间看似相当
简单的东西,但我似乎无法工作.我正在构建一个
从Web主机检索数据的iPhone应用程序.我正在尝试
建立与主机的异步连接,因为我想
在连接期间保持设备释放.(sendSynchronousRequest
将手机冻结,直到请求完成.)这是我的连接代码:

//temp url to see if data is returned:
NSURL *theURL = [NSURL URLWithString:@"http://www.theappleblog.com/feed"];

NSURLRequest *dataRequest = [NSURLRequest requestWithURL:theURL
             cachePolicy:NSURLRequestReloadIgnoringLocalCacheData
             timeoutInterval:60];

/* establish the connection */  
theConnection = [[NSURLConnection alloc]
                 initWithRequest:dataRequest
                        delegate:self
                startImmediately:YES];

if (theConnection == nil) { 
    NSLog(@"Connection Failure!");
    self.urlData = nil; 
} else {
    self.urlData = [[NSMutableData data] retain];   
}
Run Code Online (Sandbox Code Playgroud)

我已经设置了所有适当的委托方法:

-(void)connection:(NSURLConnection *)connection
       didReceiveResponse:(NSURLResponse*)response
{
    [urlData setLength:0];
    UIApplication *application = [UIApplication sharedApplication];
    application.networkActivityIndicatorVisible = YES;
    NSLog(@"Received Response!");
}
Run Code Online (Sandbox Code Playgroud)

-(void)connection:(NSURLConnection *)connection
       didReceiveData:(NSData*)incrementalData
{
    [self.urlData appendData:incrementalData];

    NSNumber *resourceLength = [NSNumber
              numberWithUnsignedInteger:[self.urlData length]];
    NSLog(@"resourceData length: %d", [resourceLength intValue]);
    NSLog(@"filesize: %d", self.urlDataSize);
    NSLog(@"float filesize: %f", [self.urlDataSize floatValue]);
}
Run Code Online (Sandbox Code Playgroud)

-(void)connectionDidFinishLoading:(NSURLConnection*)connection
{
    NSLog(@"Connection finished loading\n");
    NSLog(@"Succeeded! Received %d bytes of data",[urlData length]);
    _isFinished = YES;
    UIApplication *application = [UIApplication sharedApplication];
    application.networkActivityIndicatorVisible = NO;
}
Run Code Online (Sandbox Code Playgroud)

- (void)connection:(NSURLConnection *)connection
        didFailWithError:(NSError *)error
{
    NSLog(@"Error: %@",[error localizedDescription]);
}
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,我有一大堆日志消息,因为我想
知道是否有任何事情发生.我的连接测试
返回为TRUE但没有数据被加载.就像我说的,我确信
我必须做(或不做)一些非常愚蠢的事情.但是什么?
非常感激任何的帮助.

谢谢,劳伦斯

Ale*_*lds 0

这并不能直接回答您的问题,但您可能会考虑查看 Ben Copsey 的ASIHTTPRequest库,该库包装了CFNetwork类并包含异步、线程请求代码,这些代码需要大量工作才能正确完成此操作。