문제

I have the following method to get the content of a file called parsertest.html from a webserver. However about one every 5 times i run my program, the fetched NSString contains a line of pipes at the end

||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

Here is my code:

-(NSString *)fetchTest
 {


NSURL* url = [NSURL URLWithString:@"http://www.mywebserver.com/parsertest.html"];


NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setValue:scraperUserAgent forHTTPHeaderField:@"User-Agent"];

NSURLResponse* response = nil;
NSError* error = nil;
NSData* data = [NSURLConnection sendSynchronousRequest:request
                                     returningResponse:&response
                                                 error:&error];

NSString *dataInStringFormat = [NSString stringWithUTF8String:[data bytes]];


NSLog(@"%@",dataInStringFormat);
return dataInStringFormat;

}

scraperUserAgent is set to "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:15.0) Gecko/20100101 Firefox/15.0"

This is the content of parsertest.html

<parse>HELLO</parse>
<parse>World</parse>
<parse>digit</parse>
<parse>wow</parse>
<parse>hellonewitem</parse>
<parse>lastitem</parse>

this is the complete output of NSLog when the error occurs:

<parse>HELLO</parse>
<parse>World</parse>
<parse>digit</parse>
<parse>wow</parse>
<parse>hellonewitem</parse>
<parse>lastitem</parse>
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||

Thanks for any help!

Matthias

도움이 되었습니까?

해결책

stringWithUTF8String expects a NULL-terminated C string, but [data bytes] is not NULL-terminated. Use

NSString *dataInStringFormat = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];

instead.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top