为什么NSURL Connection Received Data包含字节,但在转换为NSString时,字符串是Null?

时间:2014-07-16 20:32:08

标签: ios encoding nsstring nsurlconnection nsdata

我已尝试过其他帖子中的很多其他解决方案,但未成功从我收到的数据中获取字符串。除了我在另一个文件上运行几乎一个副本,它100%的时间工作。它甚至从完全相同的php文件中获取数据。

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

    [imagesTableData appendData:data];
    NSString *dataStringImages = [[NSString alloc] initWithData:imagesTableData encoding:NSUTF8StringEncoding];
    receivedDataImages = [NSString stringWithFormat:@"%@%@",receivedDataImages,dataStringImages];

}

+ (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"%lu -- %@",(unsigned long)[imagesTableData length],receivedDataImages);
}

NSLog输出:14938 - (null)

enter image description here

我通过更改编码修复了我的问题:NSUTF8StringEncoding到encoding:NSASCIIStringEncoding。请参阅下面对didReceiveData的修复:

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

    [imagesTableData appendData:data];
    NSString *dataStringImages = [[NSString alloc] initWithData:imagesTableData encoding:NSASCIIStringEncoding];
    receivedDataImages = [NSString stringWithFormat:@"%@%@",receivedDataImages,dataStringImages];

}

现在我知道为什么这是修复?让我解释是什么让我如此困惑。我有两个不同但相似的实用程序文件,我用来接收解析数据,然后将它们放入数据库。

问题是两个文件都连接到同一个PHP文件,并且PHP文件以不同的数据量完全相同地输出数据。为什么需要编码" NSUTF8StringEncoding"和另一个" NSASCIIStringEncoding"?

请参阅下面的代码以及每个实用程序文件的相关数据输出。

效用文件A

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

    [placesTableData appendData:data];
    NSString *dataStringPlaces = [[NSString alloc] initWithData:placesTableData encoding:NSUTF8StringEncoding];
    receivedDataPlaces = [NSString stringWithFormat:@"%@%@",receivedDataPlaces,dataStringPlaces];

}

效用数据A

MERRYMAN|Merryman Performing Arts Center|LOC|40.698903|-99.085779|||Mention this coupon when ordering for 20% off tickets at the Merryman Performing Arts Center.|308-698-8297||http://www.merrymancenter.org|225 West 22nd Street Kearney, NE 68845||0000-00-00 00:00:00|0000-00-00 00:00:00|0|2014-07-16 21:29:51~~

效用文件B

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

    [imagesTableData appendData:data];
    NSString *dataStringImages = [[NSString alloc] initWithData:imagesTableData encoding:NSASCIIStringEncoding];
    receivedDataImages = [NSString stringWithFormat:@"%@%@",receivedDataImages,dataStringImages];

}

效用输出B

WSGFFJKM|LIPS Printing Service 25% Off|LIPSNewCustomerAd2014_KearneyApp.jpg||LIPSPRINTING2|2014-07-16 23:46:07~~

如果您对如何或是否应该重写我的问题有任何意见,请在评论中提出建议。

1 个答案:

答案 0 :(得分:1)

来自initWithData:encoding:的{​​{3}}:

  

如果由于某种原因初始化失败,则返回nil(例如   如果数据不代表编码的有效数据。)

仔细检查您的数据是否具有正确的编码或字符串。您可能希望推迟将数据转换为字符串,直到连接完成加载后