Question

I am uploading a file to a server, using NSStream APIs to read in chunks. I'm trying to display a progress bar showing upload progress. I'm unable to find a reliable solution for determining the number of bytes read into the file. Changing file and chunk size, I still keep getting either the total bytes, or something strange such as 93 or 212 for bytes read. Does anyone have any tips for trying to accomplish this? It seems like it should be simple.

  // create the write stream
    NSOutputStream *outputStream = [NSOutputStream outputStreamToFileAtPath:uploadTempFilename append:NO];
    [outputStream open];

    const char *UTF8String;
    size_t writeLength;
    UTF8String = [multipartBegin UTF8String];
    writeLength = strlen(UTF8String);

    size_t __unused actualWrittenLength;
    actualWrittenLength = [outputStream write:(uint8_t *)UTF8String maxLength:writeLength];

    NSLog(@"actualWrittenLength1 %d bytes)", actualWrittenLength);//this will be 908
    // open the input stream
    const size_t bufferSize = 128 ;
    size_t readSize = 0;
    uint8_t *buffer = (uint8_t *)calloc(1, bufferSize);

    [inImageStream open];
    while ([inImageStream hasBytesAvailable]) {
        if (!(readSize = [inImageStream read:buffer maxLength:bufferSize])) {
            break;
        }


     size_t __unused actualWrittenLength;


        actualWrittenLength = [outputStream write:buffer maxLength:readSize];

        NSLog(@"actualWrittenLength2 %d bytes)", actualWrittenLength);//this always outputs 128, until the last call which will be something like 22


    }

    //NSLog(@"NSStreamFileCurrentOffsetKey %d", [outputStream valueForKey:NSStreamFileCurrentOffsetKey]);
    [inImageStream close];
    free(buffer);


    UTF8String = [multipartEnd UTF8String];
    writeLength = strlen(UTF8String);
    actualWrittenLength = [outputStream write:(uint8_t *)UTF8String maxLength:writeLength];

    NSLog(@"actualWrittenLength3 %d bytes)", actualWrittenLength);//this will always be 42

[outputStream close];



    NSInputStream *inputStream = [NSInputStream inputStreamWithFileAtPath:uploadTempFilename];

    [HTTPRequest setContentType:contentType];
    return [HTTPRequest performMethod:@"POST" onURL:url withInputStream:inputStream knownContentSize:fileSize];
Was it helpful?

Solution

Have you tried the property value of NSStreamFileCurrentOffsetKey?

CF-APIs may also be worth looking at.

If needed, you could subclass -[NSOutputStream write:maxLength:] to track the present position.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top