Objective c - Writing image file to ip address - objective-c

Experts:
I've been researching all morning on how to write an image file to another computer via IP Address. Do I really need to create sockets, set delegates, schedule a run loop, check space available, and all that hoopla? Really? Can't I just save the file to a URL using the IP Address and default port?
I'm asking this question because I'm not making much progress on my own and I know the minute I hit Post Your Question I'll find some useful information. But in case that does not happen, please reply. Any help is appreciated.
This is the code I have and I think I'm on the wrong track:
#import "TESTtcpController.h"
#interface TESTtcpController()
#property (nonatomic, strong)NSInputStream *inputStream;
#property (nonatomic, strong)NSOutputStream *outputStream;
//void CFStreamCreatePairWithSocketToHost (
// CFAllocatorRef alloc,
// CFStringRef host,
// UInt32 port,
// CFReadStreamRef *readStream,
// CFWriteStreamRef *writeStream
// );
#end
#implementation TESTtcpController
+ (void)sendFile:(UIImage *)image
{
UInt32 port = 80;
NSString *ipAddress = #"10.10.10.10";
TESTtcpController *tcpController = [[TESTtcpController alloc] init];
[tcpController connect:port ipAddress:ipAddress];
[tcpController postFile:image];
[tcpController disconnect];
tcpController = nil;
}
-(void)connect:(UInt32)port ipAddress:(NSString *)ipAddress
{
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)ipAddress, port, &readStream, &writeStream);
self.inputStream = (__bridge NSInputStream *)readStream;
self.outputStream = (__bridge NSOutputStream *)writeStream;
[self.inputStream setDelegate:self];
[self.outputStream setDelegate:self];
[self.inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self.outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self.inputStream open];
[self.outputStream open];
NSLog(#"input stream id %#", self.inputStream);
/* Store a reference to the input and output streams so that
they don't go away.... */
}
- (void)postFile:(UIImage *)image
{
}
- (void)dataSending:(NSString*)data {
if(self.outputStream) {
if(![self.outputStream hasSpaceAvailable])
return;
NSData *_data=[data dataUsingEncoding:NSUTF8StringEncoding]; int data_len = [_data length];
uint8_t *readBytes = (uint8_t *)[_data bytes];
int byteIndex=0;
unsigned int len=0;
while (TRUE) {
len = ((data_len - byteIndex >= 40960) ? 40960 : (data_len-byteIndex));
if(len==0)
break;
uint8_t buf[len]; (void)memcpy(buf, readBytes, len);
len = [self.outputStream write:(const uint8_t *)buf maxLength:len]; byteIndex += len;
readBytes += len; }
}
}
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode
{
switch(eventCode) {
case NSStreamEventNone:
break;
case NSStreamEventOpenCompleted:
break;
case NSStreamEventHasBytesAvailable:
break;
case NSStreamEventHasSpaceAvailable:
// {
// uint8_t *readBytes = (uint8_t *)[_data mutableBytes];
// readBytes += byteIndex; // instance variable to move pointer
// int data_len = [_data length];
// unsigned int len = ((data_len - byteIndex >= 1024) ?
// 1024 : (data_len-byteIndex));
// uint8_t buf[len];
// (void)memcpy(buf, readBytes, len);
// len = [stream write:(const uint8_t *)buf maxLength:len];
// byteIndex += len;
// break;
// }
case NSStreamEventErrorOccurred:
break;
case NSStreamEventEndEncountered:
break;
// continued ...
}
}
-(void)disconnect{
NSLog(#"disconnect method called");
NSStreamStatus socketStatus = [self.outputStream streamStatus];
int status = socketStatus;
NSLog(#"Stream Status is %i", status);
if (status == 2) {
[self.inputStream close];
[self.outputStream close];
NSLog(#"Socket Closed");
}
}
- (void)deallocMe
{
[TESTtcpController dealloc];
}
#end

You should use the AFNetworking library. Image uploads will be trivial. Read about AFNetworking here: http://cocoadocs.org/docsets/AFNetworking/2.0.0/
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
NSURL *URL = [NSURL URLWithString:#"http://example.com/upload"];
NSURLRequest *request = [NSURLRequest requestWithURL:URL];
NSURL *filePath = [NSURL fileURLWithPath:#"file://path/to/image.png"];
NSURLSessionUploadTask *uploadTask = [manager uploadTaskWithRequest:request fromFile:filePath progress:nil completionHandler:^(NSURLResponse *response, id responseObject, NSError *error) {
if (error) {
NSLog(#"Error: %#", error);
} else {
NSLog(#"Success: %# %#", response, responseObject);
}
}];
[uploadTask resume];

Related

Objective c: Send audio data in rtp packet via socket

In my app, I have to capture microphone and send audio data in rtp packet. But I only see receive rtp data like iOS RTP live audio receiving or unanswered one.
I used following code with AsuncUdpSocket to sent audio data but it wasn't wrap in rtp packet. Is there any library to wrap my audio data into rtp packet?
initial AsyncUdpSocket:
udpSender = [[GCDAsyncUdpSocket alloc] initWithDelegate:self delegateQueue:dispatch_get_main_queue()];
NSError *error;
[udpSender connectToHost:#"192.168.1.29" onPort:1024 error:&error];
I send audio data in my playback callback function:
static OSStatus playbackCallback(void *inRefCon,
AudioUnitRenderActionFlags *ioActionFlags,
const AudioTimeStamp *inTimeStamp,
UInt32 inBusNumber,
UInt32 inNumberFrames,
AudioBufferList *ioData) {
/**
This is the reference to the object who owns the callback.
*/
AudioProcessor *audioProcessor = (AudioProcessor*) inRefCon;
// iterate over incoming stream an copy to output stream
for (int i=0; i < ioData->mNumberBuffers; i++) {
AudioBuffer buffer = ioData->mBuffers[i];
// find minimum size
UInt32 size = min(buffer.mDataByteSize, [audioProcessor audioBuffer].mDataByteSize);
// copy buffer to audio buffer which gets played after function return
memcpy(buffer.mData, [audioProcessor audioBuffer].mData, size);
// set data size
buffer.mDataByteSize = size;
//Send data to remote server
NSMutableData *data=[[NSMutableData alloc] init];
Float32 *frame = (Float32*)buffer.mData;
[data appendBytes:frame length:size];
if ([udpSender isConnected])
{
[udpSender sendData:data withTimeout:-1 tag:1];
}
}
return noErr;
}
How do I accomplish this?
Thanks.
Finally, here's my solution.
Setup the microphone capture process:
-(void)open {
NSError *error;
m_capture = [[AVCaptureSession alloc]init];
AVCaptureDevice *audioDev = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeAudio];
if (audioDev == nil)
{
printf("Couldn't create audio capture device");
return ;
}
//m_capture.sessionPreset = AVCaptureSessionPresetLow;
// create mic device
AVCaptureDeviceInput *audioIn = [AVCaptureDeviceInput deviceInputWithDevice:audioDev error:&error];
if (error != nil)
{
printf("Couldn't create audio input");
return ;
}
// add mic device in capture object
if ([m_capture canAddInput:audioIn] == NO)
{
printf("Couldn't add audio input");
return ;
}
[m_capture addInput:audioIn];
// export audio data
AVCaptureAudioDataOutput *audioOutput = [[AVCaptureAudioDataOutput alloc] init];
[audioOutput setSampleBufferDelegate:self queue:dispatch_get_main_queue()];
if ([m_capture canAddOutput:audioOutput] == NO)
{
printf("Couldn't add audio output");
return ;
}
[m_capture addOutput:audioOutput];
[audioOutput connectionWithMediaType:AVMediaTypeAudio];
[m_capture startRunning];
return ;
}
Capture the microphone data:
-(void) captureOutput:(AVCaptureOutput *)captureOutput didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection{
char szBuf[450];
int nSize = sizeof(szBuf);
if (isConnect == YES)
{
if ([self encoderAAC:sampleBuffer aacData:szBuf aacLen:&nSize] == YES)
{
[self sendAudioData:szBuf len:nSize channel:0];
}
}
Initial the socket
-(void)initialSocket{
//Use socket
printf("initialSocket\n");
CFReadStreamRef readStream = NULL;
CFWriteStreamRef writeStream = NULL;
NSString *ip = #"192.168.1.147"; //Your IP Address
uint *port = 22133;
CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, (__bridge CFStringRef)ip, port, &readStream, &writeStream);
if (readStream && writeStream) {
CFReadStreamSetProperty(readStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
CFWriteStreamSetProperty(writeStream, kCFStreamPropertyShouldCloseNativeSocket, kCFBooleanTrue);
iStream = (__bridge NSInputStream *)readStream;
[iStream setDelegate:self];
[iStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[iStream open];
oStream = (__bridge NSOutputStream *)writeStream;
[oStream setDelegate:self];
[oStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[oStream open];
}
}
Send data to socket when capture the data form microphone.
-(void)sendAudioData: (char *)buffer len:(int)len channel:(UInt32)channel
{
Float32 *frame = (Float32*)buffer;
[globalData appendBytes:frame length:len];
if (isConnect == YES)
{
if ([oStream streamStatus] == NSStreamStatusOpen)
{
[oStream write:globalData.mutableBytes maxLength:globalData.length];
globalData = [[NSMutableData alloc] init];
}
}
}
Hope this will help someone.

Socket Programming in Objective-C

currently I am wanting to program a chat server. I am having trouble really understanding the documentations though.
Currently, this is my code, basically extracted from the developer library:
#import "ServerSide.h"
#implementation ServerSide
#synthesize socket;
#synthesize socketAddress;
#synthesize handleConnect;
#synthesize portNumber;
- (id)init{
self = [super init];
if (self) {
self.socket = CFSocketCreate(kCFAllocatorDefault, PF_INET, SOCK_STREAM, IPPROTO_TCP, kCFSocketAcceptCallBack, handleConnect, NULL);
}
return self;
}
- (void) bind {
memset(&socketAddress, 0, sizeof(socketAddress));
socketAddress.sin_len = sizeof(socketAddress);
socketAddress.sin_family = AF_INET; /* Address family */
socketAddress.sin_port = htons(self.portNumber); /* Or a specific port */
socketAddress.sin_addr.s_addr= INADDR_ANY;
CFDataRef sincfd = CFDataCreate(kCFAllocatorDefault, (UInt8 *)&socketAddress, sizeof(socketAddress));
CFSocketSetAddress(socket, sincfd);
CFRelease(sincfd);
}
- (void) listen {
CFRunLoopSourceRef socketsource = CFSocketCreateRunLoopSource(kCFAllocatorDefault, socket, 0);
CFRunLoopAddSource(CFRunLoopGetCurrent(), socketsource, kCFRunLoopDefaultMode);
CFSocketGetNative(socket);
}
Now, 'handleconnect' is a CFSocketCallBack ivar with no initialization.
Now I have seen others use different implementations to creating a socket server but this was the one from the docs and I would like to build on top of that.
I am currently attempting to connect to the server but it looks like this doesn't even open a socket. I can't seem to connect to it through terminal using telnet localhost 'port#' either.
Heres the client implementation:
#import "Client.h"
#implementation Client
#synthesize host;
#synthesize port;
#synthesize readStream;
#synthesize writeStream;
#synthesize inputStream;
#synthesize outputStream;
- (void)setup {
NSLog(#"Setting up connection to %# : %i", [[NSURL URLWithString:host] absoluteString], port);
CFStreamCreatePairWithSocketToHost(kCFAllocatorDefault, (__bridge CFStringRef)[[NSURL URLWithString:host] host], port, &readStream, &writeStream);
if(!CFWriteStreamOpen(writeStream)) {
NSLog(#"Error, writeStream not open");
return;
}
}
- (void)open {
NSLog(#"Opening streams.");
inputStream = (__bridge_transfer NSInputStream *)readStream;
outputStream = (__bridge_transfer NSOutputStream *)writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open];
}
- (void)close {
NSLog(#"Closing streams.");
[inputStream close];
[outputStream close];
[inputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream setDelegate:nil];
[outputStream setDelegate:nil];
inputStream = nil;
outputStream = nil;
}
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)event {
NSLog(#"Stream triggered.");
switch(event) {
case NSStreamEventHasSpaceAvailable: {
if(stream == outputStream) {
NSLog(#"outputStream is ready.");
}
break;
}
case NSStreamEventHasBytesAvailable: {
if(stream == inputStream) {
NSLog(#"inputStream is ready.");
uint8_t buf[1024];
unsigned int len = 0;
len = (int)[inputStream read:buf maxLength:1024];
if(len > 0) {
NSMutableData* data=[[NSMutableData alloc] initWithLength:0];
[data appendBytes:(const void *)buf length:len];
[self readIn:[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding]];
data = nil;
}
}
break;
}
default: {
NSLog(#"Stream is sending an Event: %lu", event);
break;
}
}
}
- (void)readIn:(NSString *)s {
NSLog(#"Reading in the following:");
NSLog(#"%#", s);
}
- (void)writeOut:(NSString *)s {
uint8_t *buf = (uint8_t *)[s UTF8String];
[outputStream write:buf maxLength:strlen((char *)buf)];
NSLog(#"Writing out the following:");
NSLog(#"%#", s);
}
#end
I run the server on a specified port, then tell the client to connect to the specified host and port number.
But now how do I pass data in the socket I have opened...
I don't expect some large explanation, but if someone could give me a better understanding of what needs to be done to further this implementation, I'd greatly appreciate it.

NSInputStream not opening stream/ How to post data when setting up stream

What I am trying to do: I have a url request (post) where I send some information to a api server which then starts streaming data in bytes to me.
1) How do I post data when trying to set up a stream as right now I am just using a url, can I incorporate a NSURLRequest some how?
2) Why isnt my stream even opening (streamStatus returns 0) and thus - (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode never being called? , this is my best attempt and for the most part following this Guide
- (void)setUpStreamFromURL:(NSURL *)path {
// iStream is NSInputStream instance variable
iStream = [[NSInputStream alloc] initWithURL:path];
[iStream setDelegate:self];
[iStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
[iStream open];
NSLog(#"Stream Open: %lu",[iStream streamStatus]); //return 0
}
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode {
NSLog(#"Streaming");
switch(eventCode) {
case NSStreamEventHasBytesAvailable:
{
if(!_data) {
_data = [[NSMutableData data] init];
}
uint8_t buf[1024];
unsigned int len = 0;
len = [(NSInputStream *)stream read:buf maxLength:1024];
if(len) {
[_data appendBytes:(const void *)buf length:len];
NSLog(#"DATA BEING SENT : %#", _data);
// bytesRead is an instance variable of type NSNumber.
// [bytesRead setIntValue:[bytesRead intValue]+len]; //getting error that setInt value is not part of NSNumber, and thats true so not sure what to do about it, but this isn't the issue.
} else {
NSLog(#"no buffer!");
}
break;
}
case NSStreamEventEndEncountered:
{
[stream close];
[stream removeFromRunLoop:[NSRunLoop currentRunLoop]
forMode:NSDefaultRunLoopMode];
stream = nil; // stream is ivar, so reinit it
break;
}
// continued ...
}
}
also incase it helps, my header file:
#import <Foundation/Foundation.h>
#import "Login.h"
#interface Stream : NSStream <NSStreamDelegate> {
NSMutableArray *searchIdList;
NSInputStream *iStream;
NSNumber *bytesRead;
}
- (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode ;
-(id)initWithLoginObject:(Login *)log;
#property NSMutableData *data;
#end
You can't use NSURLRequest in Stream.
To create a request you can use this.
request = CFHTTPMessageCreateRequest(kCFAllocatorDefault, CFSTR("POST"),(CFURLRef) url, kCFHTTPVersion1_1);
CFHTTPMessageSetHeaderFieldValue(request, CFSTR("User-Agent"), CFSTR("MSControl-US"));
CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Content-Type"), CFSTR("application/json"));
CFHTTPMessageSetHeaderFieldValue(request, CFSTR("Connection"), CFSTR("Keep-Alive"));
After that you can create the stream using
readStream = CFReadStreamCreateForHTTPRequest(kCFAllocatorDefault, request)
or if you already have an opened stream you can serialize your request With :
NSData *data = (NSData *)CFHTTPMessageCopySerializedMessage(request);
and send with This:
length = [data length];
CFWriteStreamWrite((CFWriteStreamRef)outStream,data,lenght);
Hope this help

NSJSONSerialization error

I'm trying to send json object to server. But I received an error and I can't fix it.
-(void) connectToHost{
CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (CFStringRef)#"localhost", 9123, &readStream, &writeStream);
inputStream = (__bridge NSInputStream *)readStream;
outputStream = (__bridge NSOutputStream *)writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[inputStream open];
[outputStream open]; }
This is my connection to host.
NSDictionary *setUser = [NSDictionary
dictionaryWithObjectsAndKeys:[#"u" stringByAppendingString:my.id],#"id",
#"GET_USER_INFO",#"command",
#"",#"value",
nil];
NSArray *array = [NSArray arrayWithObject:setUser];
jsonDataToSendTheServer = [array JSONRepresentation];
NSLog(#" %# ", jsonDataToSendTheServer);
// array = [NSArray arrayWithObject:jsonDataToSendTheServer];
NSLog(#" %# ", array);
NSLog(#"true or false %c",[NSJSONSerialization
isValidJSONObject: array]);
bytesWritten = [NSJSONSerialization writeJSONObject:array toStream:outputStream options:NSJSONWritingPrettyPrinted error:nil];
and this part is NSJSONSerialization part.
However I got an error.
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '***+[NSJSONSerialization writeJSONObject:toStream:options:error:]: stream is not open for writing'
I'm new at objective-c. I can't fix the problem for 3 hours.
=======================================
edit:
- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {
NSLog(#"stream event %i", streamEvent); //this doesn't post in the log when stream opened...
NSLog(#"bytes %i",bytesWritten);
switch (streamEvent) {
case NSStreamEventOpenCompleted:
NSLog(#"Stream opened");
break;
case NSStreamEventHasBytesAvailable:
if (theStream == inputStream) {
uint8_t buffer[1024];
int len;
while ([inputStream hasBytesAvailable]) {
len = [inputStream read:buffer maxLength:sizeof(buffer)];
if (len > 0) {
NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSUTF8StringEncoding];
if (nil != output) {
NSLog(#"server said: %#", output);
//[self messageReceived:output];
}
}
}
}
break;
case NSStreamEventEndEncountered:
[theStream close];
[theStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
//[theStream release];
theStream = nil;
break;
case NSStreamEventHasSpaceAvailable:
{
uint8_t *readBytes = (uint8_t *)[_data mutableBytes];
readBytes += bytesWritten; // instance variable to move pointer
int data_len = [_data length];
unsigned int len = ((data_len - bytesWritten >= 1024) ?
1024 : (data_len-bytesWritten));
uint8_t buf[len];
(void)memcpy(buf, readBytes, len);
//len = [theStream write:(const uint8_t *)buf maxLength:len];
NSLog(#"written %s", buf );
bytesWritten += len;
}
break;
case NSStreamEventErrorOccurred:
{
NSLog(#"no connection");
}
case NSStreamEventNone:
{
//printf("EVENT: None.\n");
break;
}
default:
NSLog(#"Unknown event");
}}
this is my stream: handleEvent: function.
Now after I did add the connectionToHost to delegate I get this kind of error.
012-08-10 16:14:27.302 TaraftarlikOyunu[2274:c07] written P∏◊P‡ˇø
2012-08-10 16:14:28.399 TaraftarlikOyunu[2274:c07] benim bu id 587127341
2012-08-10 16:14:28.399 TaraftarlikOyunu[2274:c07] benim ad Ahmet
2012-08-10 16:14:28.400 TaraftarlikOyunu[2274:c07]
[{"id":"u581277341","command":"GET_USER_INFO","value":""}]
2012-08-10 16:14:28.404 TaraftarlikOyunu[2274:c07] stream event 4
2012-08-10 16:14:28.404 TaraftarlikOyunu[2274:c07] bytes 86
(lldb)
now I don't have an idea that if it buffered or not
=======================EDIT2===============
sorry about this.
the problem probably appears because of this
(void)memcpy(buf, readBytes, len);
I just copy and paste this part of code.
what may be the problem!
The connection method you are using is a little much.
You need to make sure the connection has happened in the delegate
- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {
switch (streamEvent) {
case NSStreamEventHasSpaceAvailable:
NSLog(#\"None!\");
break;
case NSStreamEventOpenCompleted:
NSLog(#\"Stream opened\");
//NOW you can write to the stream

Convert inputstream to textfield.text objective-c

I have some problem with my objective-c app. I want to convert input stream to textfield.text in objective-c.
I have tcp client with input stream and output stream. I want to use data from input stream and show them in uitextfield.
Can I use something like that:
temperatura.text = [inputStream read:buffer maxLength:sizeof(buffer)];
- (void)stream:(NSStream *)theStream handleEvent:(NSStreamEvent)streamEvent {
NSLog(#"stream event %i", streamEvent);
switch (streamEvent) {
case NSStreamEventOpenCompleted:
NSLog(#"Stream opened");
break;
case NSStreamEventHasBytesAvailable:
if (theStream == inputStream) {
uint8_t buffer[1024];
int len;
while ([inputStream hasBytesAvailable]) {
len = [inputStream read:buffer maxLength:sizeof(buffer)];
if (len > 0) {
NSString *output = [[NSString alloc] initWithBytes:buffer length:len encoding:NSASCIIStringEncoding];
if (nil != output) {
NSLog(#"server said: %#", output);
}
}
}
}
break;
I'm using this client. I want to use data from 'output' to get them on textfield.
Following line of code will return an int
[inputStream read:buffer maxLength:sizeof(buffer)]
Following line of code needs a NSString not int
temperatura.text
So you will have to typecast [inputStream read:buffer maxLength:sizeof(buffer)] to a string before you assign to temperatura.text . You can use following to typecast:
temperatura.text = [NSString stringWithFormat:#"%d",[inputStream read:buffer maxLength:sizeof(buffer)]];
A simple typecast example is :
NSString *string = [NSString stringWithFormat:#"%d", theinteger];
Please note that I have not tested this code for proper syntax, but this could be a solution. Let me know if you face any problems.
Thanks
Refer Folowing Code
(void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode {
switch(eventCode) {
case NSStreamEventHasBytesAvailable:
{
if(!_data) {
_data = [[NSMutableData data] retain];
}
uint8_t buf[1024];
unsigned int len = 0;
len = [(NSInputStream *)stream read:buf maxLength:1024];
if(len) {
[_data appendBytes:(const void *)buf length:len];
// bytesRead is an instance variable of type NSNumber.
[bytesRead setIntValue:[bytesRead intValue]+len];
} else {
NSLog(#"no buffer!");
}
break;
**
temperatura.text = [[NSString alloc] initWithBytes:[_data bytes] length:[_data length] encoding:NSUTF8StringEncoding]
**