objective-cuibuttonnsoutputstream

Using NSOutputStream to output the current time to the Server


I'm Using NSOutputStream to Output data from the client (IOS device ) to the server (PC Device). I can send data successfully to the server, I just want to add the Current Time using NSOutputStream.

How can i send the current time using NSOutputStream?

Here's my code

- (IBAction)button1:(id)sender {

    NSString *response  = @" Today's Sunny  \n  ";
    NSData *data = [[NSData alloc] initWithData:[response dataUsingEncoding:NSASCIIStringEncoding]];
    [outputStream write:[data bytes] maxLength:[data length]];

    NSDate *currentTime = [NSDate date]; 
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"hh:mm:ss"];
    _timer.text = [formatter stringFromDate:currentTime];
    //_timer is A label just for testing
    ///I'm trying to use outputStream to output currentTime like this
   /// [outputStream write:[currentTime bytes] maxLength:[CurrentTime length]];
}

Solution

  • You need to convert the formatted time string to data, the way you are already doing with the response, as long as the other side of the stream is just expecting text. It can often be easier to use the -UTF8String method directly instead of using NSData:

    [outputStream write:[string UTF8String]
              maxLength:[string lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
    

    In the end, you are sending over raw bytes on an NSStream. NSData is obvious how to do that, but you need to get the exact c-string length if you are using character bytes -- so you can use the UTF8String and strlen() of that, or the lengthOfBytesUsingEncoding method as above.