Pergunta

Im trying to send a string using NSoutputstream , however i cant seem to get the encoding right , using dataWithContentsOfURL works

im using a nodejs TCP server with actionHero library.

it works using netcat and telnet.

- (IBAction)sendText:(id)sender {
NSString *response  = [NSString stringWithFormat:@"%@", [_sendTextField.text stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];
NSLog(@"writing %@",response);

///////////////////////////// this line works/////////////////////////////////////////////////////
//  NSData *data = [[NSData alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL   URLWithString:@"http://www.google.com"]]];


///////////////////////////// this line doesnt work/////////////////////////////////////////////////////
NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSUTF8StringEncoding]];


//%u returns a non zero value
NSLog(@"%u",[outputStream write:[data bytes] maxLength:[data length]]);
}

i get a null streamError from handle stream Event method

Foi útil?

Solução 2

Found the answer to my own question. turns out the problem is in actionHero's on data method where it looks for a /n which is not provided by the ios application. appended a \n and its fine now

Outras dicas

Not knowing the content of response, I can't give you a specific answer as to why NSUTF8StringEncoding doesn't work with it. Generally speaking, however, if there is a byte sequence in your content that is incompatible with UTF-8, you're going to get nil when you call -dataUsingEncoding:.

There's a strategy that I learned from reading Mike Ash's blog (look under the section "Fallbacks"), and it's served me pretty well in situations such as yours.

To briefly sum it up, first try using NSUTF8StringEncoding. If that doesn't work, try using NSISOLatin1StringEncoding. And if that doesn't work, try using NSMacOSRomanStringEncoding. Mike's blog has the rationale for this.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top