简体   繁体   English

NSMutableData到NSString给出nil

[英]NSMutableData to NSString give nil

I am using my app NSURLConnection for getting webpage of a site. 我正在使用我的应用程序NSURLConnection获取网站的网页。

this how i call the NSURLConnection 这就是我所说的NSURLConnection

NSURL *url = [NSURL URLWithString:@"http://jokes.moment.co.il/default.asp?s1=4&s2=0"];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    [NSURLConnection connectionWithRequest:request delegate:self];

this is how i append the data that i get: 这就是我附加我得到的数据的方式:

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

and this is how i try to convert it to NSString: 这就是我尝试将其转换为NSString的方法:

-(void) connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSString *string = [[NSString alloc] initWithData:receivedData encoding:NSUTF8StringEncoding];
}

the receivedData is 47586 bytes and when i do the convert the string is nil receiveData是47586字节,当我执行转换时,字符串为nil

A quick look at the content for your URL show that the content-type is ISO-8859-1 快速查看您的URL的内容,显示内容类型为ISO-8859-1

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"/>

Try changing your call to initWithData to... 尝试将对initWithData的调用更改为...

[[NSString alloc] initWithData:nsdata encoding:NSISOLatin1StringEncoding];

More likely than not, the received string is not validly encoded as NSUTF8StringEncoding. 很有可能接收到的字符串未有效编码为NSUTF8StringEncoding。

You may need to write the string to the filesystem and then use one of the NSString methods that describes any conversion errors via an NSError** argument to know the exact error. 您可能需要将字符串写入文件系统,然后使用通过NSError**参数描述任何转换错误的NSString方法之一来了解确切的错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM