NSURLConnection不返回数据

时间:2010-01-23 10:05:05

标签: iphone cocoa nsurlconnection

我这里有一个相当不寻常的问题。下面的代码运行正常,数据发送到源正常,但没有NSURLConnection触发器返回任何内容。记录的唯一项目是发送请求的功能。有任何想法吗?

    // code starts above here

    NSData *myRequestData = [ NSData dataWithBytes: [ requestString UTF8String ] length: [ requestString length ] ];
    NSURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:urlPrefix]]; 
    [request setHTTPMethod: @"POST"];
    [request setHTTPBody: myRequestData];   
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
    NSURLResponse *resp = nil;
    NSError *err = nil;
    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse: &resp error: &err];
    NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];

    if (!theConnection)
    {
        NSLog(@"Failed to submit request");
    }
    if(theConnection)
    {
        NSMutableData* receivedData=[[NSMutableData data] retain];
        NSLog(@"Created connection.");

        NSLog(@"--------- Request submitted ---------");
        NSLog(@"receivedData: %@", receivedData);
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"Received response: %@", response);
    NSLog(@"Received response, connection retain count is %d",[connection retainCount]);
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    NSLog(@"Connection received data, retain count: %d", [connection retainCount]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    NSLog(@"finished connection retain count:  %d", [connection retainCount]);
}

1 个答案:

答案 0 :(得分:2)

这是问题所在:

NSData *response = [NSURLConnection sendSynchronousRequest:request 
                                         returningResponse:&resp 
                                                     error:&err];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:request 
                                                               delegate:self 
                                                       startImmediately:YES];

首先启动同步请求,然后再次启动请求 ,而不是异步。毫无意义。

尝试删除第一行。