Errors occur when using NSOutputStream to transfer big files

Discussion in 'iOS Programming' started by carolyn.lee, Apr 28, 2009.

  1. carolyn.lee macrumors newbie

    Feb 20, 2008
    Hi, All

    I'm trying to use the NSOutputStream class to transfer some audio file through Bonjour service which is implemented on the iPhone simulator.I try the following code with some small text files. It works well. But there are always some error occurs() when I try to send the bigger ones -- some audio file.

    Any suggestions .... ? Thanks !

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *sendFile = [documentsDirectory stringByAppendingPathComponent: @"test1.caf"];
    NSData *myData = [[[NSData alloc] initWithContentsOfFile:sendFile] autorelease];

    uint8_t *readBytes = (uint8_t *)[myData bytes];
    NSUInteger byteIndex = 0;
    int myData_len = [myData length];

    while (_outStream && [_outStream hasSpaceAvailable]) {

    readBytes += byteIndex;
    unsigned int len = ((myData_len - byteIndex >= 1024) ? 1024 : (myData_len-byteIndex));
    uint8_t buf[len];
    (void)memcpy(buf, readBytes, len);

    len = [_outStream write:(const uint8_t *)buf maxLength:len];
    byteIndex += len;

  2. kainjow Moderator emeritus


    Jun 15, 2000
    Look again at the return values for write:maxLength:. First off you aren't checking for any errors that it may give, and secondly it looks like the assignment of readBytes is being incremented too far. The memcpy() should be unnecessary as well, you could just increment a pointer and pass it directly to the stream.

    Also, when you're using -[NSData initWithContentsOfFile:], you're loading the entire file into memory. Since the iPhone has limited ram you should probably replace this with NSFileHandle, which lets you load file data incrementally.

    Oh, and put your code in between [code] ... [/code] tags - makes it easier to read.
  3. carolyn.lee thread starter macrumors newbie

    Feb 20, 2008
    I'm sorry for asking the naive questions. I'm new comer, and there are not a lot of documents detailed what I want, so I just try to pull up together the sample code to see how it works.

    kainjow, thanks a lot. I tried what you mentioned, it can send data now, but after sending out the data, the simulator terminated abnormally ....
  4. kainjow Moderator emeritus


    Jun 15, 2000

Share This Page