How to add data for NSOutputStream?

I want to convert a UIImage to an NSOutputStream and send it to the server via a socket.

#import "Connection.h" @implementation Connection -(void) open: (NSString *) h : (int) p { strHost = h; intPort = p; [NSStream getStreamsToHost:objHost port:intPort inputStream:&receiveStream outputStream:&sendStream]; [receiveStream retain]; [sendStream retain]; [receiveStream setDelegate:self]; [sendStream setDelegate:self]; [receiveStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [sendStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode]; [receiveStream open]; [sendStream open]; printf("Open.\n"); } - (void) stream: (NSStream *) stream handleEvent: (NSStreamEvent) eventCode { printf("EVENT: Start.\n"); switch(eventCode) { case NSStreamEventOpenCompleted: { printf("EVENT: Open completed.\n"); if(stream == receiveStream) { printf("Receiving...\n"); } if(stream == sendStream) { printf("Sending...\n"); NSString * strBuffer = [NSString stringWithFormat:@"GET / HTTP/1.0\r\n\r\n"]; const uint8_t * rawstring = (const uint8_t *)[strBuffer UTF8String]; [sendStream write:rawstring maxLength:strlen(rawstring)]; } break; } case NSStreamEventEndEncountered: { printf("EVENT: End encountered.\n"); break; } case NSStreamEventHasSpaceAvailable: { printf("EVENT: Has space available.\n"); break; } case NSStreamEventHasBytesAvailable: { printf("EVENT: Has bytes available.\n"); break; } case NSStreamEventErrorOccurred: { printf("EVENT: Error occurred.\n"); break; } case NSStreamEventNone: { printf("EVENT: None.\n"); break; } } printf("EVENT: End.\n"); } -(void) close { [receiveStream close]; [sendStream close]; printf("Closed.\n"); } @end 

My question is where can I add the code "sendStream = ..."?

Another question is that I can convert UIImage to NSData using:

 NSData *imageData = UIImageJPEGRepresentation(imageView.image, 90); 

But how to convert an imageData instance to an NSOutputStream instance?

+1
stream objective-c cocoa sockets
source share
1 answer

My question is, where can I add code like "sendStream = ..."?

You already assign sendStream message getStreamsToHost:port:inputStream:outputStream: This method returns two streams by reference.

... how to convert a DataData image to an NSOutputStream instance?

You do not need to convert the data to a stream, you need to tell the stream to write data.

Try the NSOutputStream write:maxLength: method . You need to pass bytes and length from the data object.

+2
source share

All Articles