2

I am working on an application that sometimes requires sending large files (500MB) or more to our servers. Generally the files will already be stored on disk and I will have the local file URL, is there a way I can create an NSMutableRequest without having to first load all the data from disk into NSData?

It would be nice just to read a few MB at a time from the disk, send it off, and then repeat until its all gone. What is the best / most efficient way to go about this?

Edit

Basically if I had a 10GB video I wanted to upload, I would never be able to fit all of it into NSData before the system terminated my app due to memory constraints.

jscs
  • 63,694
  • 13
  • 151
  • 195
Asleepace
  • 3,466
  • 2
  • 23
  • 36

1 Answers1

1

Basically, you need to read your large, local file in bits and send it over the network. You can do that using the foundation class NSInputStream.

Sample code from Apple's documentation (Objective-C):

- (void)setUpStreamForFile:(NSString *)path {
    // iStream is NSInputStream instance variable
    iStream = [[NSInputStream alloc] initWithFileAtPath:path];
    [iStream setDelegate:self];
    [iStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
                       forMode:NSDefaultRunLoopMode];
    [iStream open];
}

in Swift 3, that would be something like this:

func setUpStream(forFile path: String) -> InputStream? {
    guard let stream = InputStream(fileAtPath: path) else {
        return nil
    }
    stream.delegate = self
    stream.schedule(in: RunLoop.current, forMode: .defaultRunLoopMode)
    stream.open()

    return stream
}

(You will also need to adopt the protocol NSStreamDelegate, but this is enough to get oyu started I guess...)

Nicolas Miari
  • 16,006
  • 8
  • 81
  • 189