在ios中使用socket io发送图像

时间:2016-01-13 05:16:15

标签: ios socket.io

我使用了以下示例 https://github.com/socketio/socket.io-client-swift 如何使用socket io发送图像?

1 个答案:

答案 0 :(得分:0)

for example,you can send a image like this

//emit filename and size to server

   - (void)testButtonClicked {

     _fileName = @"001@3x.png";
     NSString *path = [[NSBundle mainBundle] pathForResource:@"001@3x" ofType:@"png"];
     _imgData = [NSData dataWithContentsOfFile:path];

     float length = [_imgData length];
     NSString *fileSizeString = [NSString stringWithFormat:@"%f", length];

    NSArray *array = [NSArray arrayWithObject:@{@"Name": _fileName, @"Size":fileSizeString}];    
    [socket emit:@"start" withItems:array];
    }


//server callback

 [socket on:@"moreData" callback:^(NSArray *array, SocketAckEmitter *emitter) {


            NSString *dataPosition = [array[0]objectForKey:@"position"];

            [self uploadAvatarImage:dataPosition];
        }];

// uploadImage Method

- (void)uploadAvatarImage:(NSString *)dataPosition {

     NSString *path = [[NSBundle mainBundle] pathForResource:@"001@3x" ofType:@"png"];
    _imgData = [NSData dataWithContentsOfFile:path];

    NSString *imageString = [[NSString alloc]initWithData:_imgData encoding:NSStringEncodingConversionAllowLossy];

    NSRange range;
    if ([dataPosition intValue]<[_imgData length]) {

        if ([_imgData length]-[dataPosition intValue]>5120) {
            range.length = 5120;
        }else {
            range.length = [_imgData length]-[dataPosition intValue];
        }

        range.location =[dataPosition intValue];
        NSString *subString = [imageString substringWithRange:range];
        NSArray *array = [NSArray arrayWithObject:@{@"Name": _fileName, @"Segment":subString}];

        [socket emit:@"upload" withItems:array];
    }
}