Question

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
Was it helpful?

Solution

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];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top