iPhone NSURLConnection - 代表不工作

时间:2010-06-29 01:21:10

标签: iphone ipad nsurlconnection

我正在尝试让NSURLConnection在我的应用中运行。我几乎完全遵循了苹果的代码,但似乎没有用。 NSURLConnection位于名为downloadSave的方法内。这个方法在最后运行正常,我的日志显示“连接存在” - 但是之后没有任何事情发生,好像没有调用任何委托方法。

NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];

    NSString *tempString = [[NSString alloc]initWithFormat:@"http://www.myWebsite.com/%@.jpg",chartFileName];
    NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:tempString]
                                              cachePolicy:NSURLRequestUseProtocolCachePolicy
                                          timeoutInterval:10.0];


    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
    if (theConnection) {


        mutableData = [[NSMutableData data] retain];
        self.image = nil;
        NSLog(@"connection exists");


    } else {
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Connection Error" message:@"There was an error contacting the servers. Please try again." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
        [alert show];
        [alert release];
        [activityIndicator stopAnimating];


    }

    [pool drain];
    [pool release];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{

    NSLog(@"got to connection did receive response");
    [mutableData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{

    [mutableData appendData:data];
    NSLog(@"got some data were at %i",mutableData.length);
}


- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error
{

    [connection release];
    // receivedData is declared as a method instance elsewhere
    self.mutableData = nil;

    NSLog(@"Connection failed! Error - %@ %@",
          [error localizedDescription],
          [[error userInfo] objectForKey:NSErrorFailingURLStringKey]);
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{

    NSLog(@"Succeeded! Received %d bytes of data",[mutableData length]);

//more code follows to display the downloaded image

}

日志中唯一出现的内容是:“连接存在”

1 个答案:

答案 0 :(得分:3)

我只能通过你的代码猜测在一个单独的线程中调用了downloadSave,因为你有一个NSAutoReleasePool(不是说你正在做什么,但很可能)。 NSURLConnection只能在主线程中初始化时响应主线程中的委托方法。

由于NSURLConnection已经是一个线程委托调用,因此您不需要在线程中创建它。如果由于某种原因需要进行处理,则应该可以使用

NSError *error;
NSURLResponse *response;
NSData *connectionData = [NSURLConnection sendSynchronousRequest:theRequest returningResponse:&response error:&error];

这应该将数据返回给子线程。