1

我正在从客户端对服务器进行异步调用,并在服务器上打印数据。但是我在客户那里得到的回应是空的

我的回复检索部分如下:-

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    [receivedData setLength:0];
    NSLog(@"connection did receive response");

}


- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // Append the new data to receivedData.
    // receivedData is an instance variable declared elsewhere
    if(!receivedData)
    {
        receivedData = [NSMutableData data];
    }

    [receivedData appendData:data];

    NSLog(@"connection did receive data");
}


- (void)connection:(NSURLConnection *)connection
  didFailWithError:(NSError *)error
{
    // inform the user
    NSLog(@"Connection failed! Error - %@ %@",

    [error localizedDescription],
    [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // receivedData is declared as a method instance elsewhere
    NSString *responseFromServer = [[NSString alloc]initWithData:receivedData encoding:NSUTF8StringEncoding]; 
    NSLog(@"connection did finish load");
    NSLog(@"response from the server=%@", responseFromServer);
 }

所以'responseFromServer'的值是空的。

谁能告诉我我哪里出错了。提前致谢。

4

2 回答 2

0

您确定receivedData包含 UTF8 编码的数据 = 字符串吗?initWithData:encoding:文档...

返回值

通过使用编码将数据中的字节转换为 Unicode 字符来初始化的 NSString 对象。返回的对象可能与原始接收者不同。如果由于某种原因初始化失败(例如,如果数据不代表用于编码的有效数据),则返回 nil。

...如您所见,如果初始化失败,它将返回 nil 。

于 2012-10-01T13:40:34.060 回答
0

如果您没有强烈引用接收数据,您可能想要开始这样做

receivedData = [NSMutableData data];是一个自动释放的对象。确保 receivedData 是一个强属性或保留属性,然后像这样设置它self.receivedData = [NSMutableData data];

在最终的 connectionDelegate 方法触发之前 receivedData 可能会自动释放,因此 responseString 在 initWithData 方法中使用 nil 数据

于 2012-10-01T17:30:26.047 回答