使用NSURLConnection异步连接,如何在main函数中获取接收到的数据?

时间:2012-04-24 12:45:52

标签: objective-c asynchronous nsurlconnection

httpController.h中的一些代码如下:

@interface httpController:NSObject{
  ...
  NSMutableData *receivedData;
}
@property (nonatomic,retain) NSMutableData *receivedData;

和httpController.m文件中的一些代码如下:

@implementation httpController
@synthesize receivedData;
...
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
  [receivedData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data               
{
  if (!receivedData) {
      receivedData = [[NSMutableData alloc] init];
  }
  [receivedData appendData:data];  
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {

}

然后我想在main.m文件中使用receivedData,如下所示:

int main(int argc, const char *argv[])
{
   HttpController *httpController = [[HttpController alloc] init];
   NSURLRequest *request = ...;
   NSURLConnection *connetion = ...;
   if(connection)
   {
     NSMutableData *_receviedData = httpController.receivedData;
     NSString * dataString = [[[NSString alloc] initWithData:_receviedData encoding:NSUTF8StringEncoding] autorelease]; 
     NSLog(@"%@",dataString);
   }
   [[NSRunLoop currentRunLoop] run];
}

但我发现在main()函数中,_receivedData的值为空,并且有输出。任何人都可以告诉我它有什么问题?

1 个答案:

答案 0 :(得分:1)

+connectionWithRequest:delegate:以异步方式运行。看起来它在返回之前没有完成连接,这就是为什么你看不到任何数据。请尝试使用+sendSynchronousRequest:returningResponse:error:,因为这将阻止线程,直到连接完成。

使用+sendSynchronousRequest:returningResponse:error:时也不需要HttpController / delegate。这是如何做到的:

int main(int argc, const char *argv[])
{
    NSURL           *url        = [NSURL URLWithString:@"http://www.yahoo.com/"];
    NSURLRequest    *request    = [NSURLRequest requestWithURL:url];
    NSURLResponse   *response   = nil;
    NSError         *error      = nil;

    // This blocks "this" thread until it's done.
    NSData          *data       = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

    if (!data)
    {
        NSLog(@"Error: %@", error);
    }
    else
    {
        NSString *dataString = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
        NSLog(@"%@", dataString);
    }
}

如果您不想阻止该帖子,那么+connectionWithRequest:delegate:就是您的选择。但是你必须以不同的方式编写代码,should read the docs