How to correctly measure NSInputStream data rate - objective-c

I'm trying to measure actual transfer speed during ftp download, download itself is working, streams are hooked up in run loop. Measurment is done in NSStreamEventHasBytesAvailable using CFTimeGetCurrent on event start and at the end, after data is written to file elapsed time is computed with (double)previousTimestamp-CFAbsoluteTimeGetCurrent, but the time I get is absolutely unreasonable. Tested on simulator and device, can anyone enlighten me?
code:
switch (eventCode) {
case NSStreamEventOpenCompleted: {
} break;
case NSStreamEventHasBytesAvailable: {
if ([[self.fileStream propertyForKey:NSStreamFileCurrentOffsetKey] intValue]==0) {
previousTimestamp = CFAbsoluteTimeGetCurrent();
}
NSInteger bytesRead;
uint8_t buffer[32768];
bytesRead = [self.networkStream read:buffer maxLength:sizeof(buffer)];
if (bytesRead == -1)
{
[self _stopReceiveWithStatus:#"Err"];
}
else if (bytesRead == 0)
{
[self _stopReceiveWithStatus:nil];
}
else
{
[self completition:bytesRead];
NSInteger bytesWritten;
NSInteger bytesWrittenSoFar;
// Write to the file.
bytesWrittenSoFar = 0;
do {
bytesWritten = [self.fileStream write:&buffer[bytesWrittenSoFar] maxLength:bytesRead - bytesWrittenSoFar];
assert(bytesWritten != 0);
if (bytesWritten == -1) {
[self _stopReceiveWithStatus:#"File err"];
break;
} else {
bytesWrittenSoFar += bytesWritten;
}
} while (bytesWrittenSoFar != bytesRead);
[self downloadSpeedSave:bytesRead :previousTimestamp-CFAbsoluteTimeGetCurrent()];
previousTimestamp = CFAbsoluteTimeGetCurrent();

An alternative that I have used is to use the time.h and c routines to capture time.
http://www.cplusplus.com/reference/clibrary/ctime/time/
Another good link on SO
iPhone: How to get current milliseconds?

Related

FFmpeg jump to most recent frame

I am looking for some help with dropping/skipping FFmpeg frames. The project I am working on streams live video which when the app goes into the background, upon returning to an active state the video stream spends a long time catching up by fast forwarding itself to the current frame. This isn't ideal and what I am aiming to achieve is have the app immediately jump to the most recent frame.
What I need to do is drop the amount of frames that are being fast-forwarded in order to catch up to the most recent frame. Is this possible? Here is my current code which decodes the frames:
- (NSArray *) decodeFrames: (CGFloat) minDuration
{
NSMutableArray *result = [NSMutableArray array];
#synchronized (lock) {
if([_reading integerValue] != 1){
_reading = [NSNumber numberWithInt:1];
#synchronized (_seekPosition) {
if([_seekPosition integerValue] != -1 && _seekPosition){
[self seekDecoder:[_seekPosition longLongValue]];
_seekPosition = [NSNumber numberWithInt:-1];
}
}
if (_videoStream == -1 &&
_audioStream == -1)
return nil;
AVPacket packet;
CGFloat decodedDuration = 0;
CGFloat totalDuration = [TimeHelper calculateTimeDifference];
do {
BOOL finished = NO;
int count = 0;
while (!finished) {
if (av_read_frame(_formatCtx, &packet) < 0) {
_isEOF = YES;
[self endOfFileReached];
break;
}
[self frameRead];
if (packet.stream_index ==_videoStream) {
int pktSize = packet.size;
while (pktSize > 0) {
int gotframe = 0;
int len = avcodec_decode_video2(_videoCodecCtx,
_videoFrame,
&gotframe,
&packet);
if (len < 0) {
LoggerVideo(0, #"decode video error, skip packet");
break;
}
if (gotframe) {
if (!_disableDeinterlacing &&
_videoFrame->interlaced_frame) {
avpicture_deinterlace((AVPicture*)_videoFrame,
(AVPicture*)_videoFrame,
_videoCodecCtx->pix_fmt,
_videoCodecCtx->width,
_videoCodecCtx->height);
}
KxVideoFrame *frame = [self handleVideoFrame];
if (frame) {
[result addObject:frame];
_position = frame.position;
decodedDuration += frame.duration;
if (decodedDuration > minDuration)
finished = YES;
}
} else {
count++;
}
if (0 == len)
break;
pktSize -= len;
}
}
av_free_packet(&packet);
}
} while (totalDuration > 0);
_reading = [NSNumber numberWithInt:0];
return result;
}
}
return result;

NSStream FTP resume file upload after NSStreamEventErrorOccurred

This code works fine, but im trying to implement a resume action after an NSStreamEventErrorOccurred, for example after internet connection lost.
What i have done is to save the number of _totalBytesSend and redo the upload only with the remaining bytes, but im facing that only the remaining bytes will be stored instead of the complete file.
I couldn't able to figure out how to resume file upload or if is there a way to merge the streams when an error ocurred?
- (void)enviar:(NSData *)aDatos pathArchivo:(NSString *)path bytesEnviados:(size_t *)aBytesEnviados
{
BOOL success;
NSURL *url;
long liBytesInicio = aBytesEnviados;
NSData *newData = [aDatos subdataWithRange:NSMakeRange(liBytesInicio, [aDatos length] - liBytesInicio)];
_currentBytesEnviados = aBytesEnviados;
_currentDatos = aDatos;
_currentPathArchivos = path;
assert(self.networkStream == nil); // don't tap send twice in a row!
assert(self.fileStream == nil); // ditto
// First get and check the URL.
url = [[NetworkManager sharedInstance] smartURLForString:[Sesion sharedSesion].configuracion.servidorFTP];
success = (url != nil);
if (success) {
// Add the last part of the file name to the end of the URL to form the final
// URL that we're going to put to.
url = CFBridgingRelease(CFURLCreateCopyAppendingPathComponent(NULL, (__bridge CFURLRef) url, (__bridge CFStringRef)path, false));
success = (url != nil);
}
// If the URL is bogus, let the user know. Otherwise kick off the connection.
// Open a stream for the file we're going to send. We do not open this stream;
// NSURLConnection will do it for us.
self.fileStream = [NSInputStream inputStreamWithData:newData];
assert(self.fileStream != nil);
[self.fileStream open];
// Open a CFFTPStream for the URL.
self.networkStream = CFBridgingRelease(CFWriteStreamCreateWithFTPURL(NULL, (__bridge CFURLRef) url));
assert(self.networkStream != nil);
success = [self.networkStream setProperty:[Sesion sharedSesion].configuracion.cuentaFTP forKey:(id)kCFStreamPropertyFTPUserName];
assert(success);
success = [self.networkStream setProperty:[Sesion sharedSesion].configuracion.passwordFTP forKey:(id)kCFStreamPropertyFTPPassword];
assert(success);
self.networkStream.delegate = self;
[self.networkStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self.networkStream open];
// Tell the UI we're sending.
}
- (void)detenerEnvio:(NSString *)estado {
if (self.networkStream != nil) {
[self.networkStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
self.networkStream.delegate = nil;
[self.networkStream close];
self.networkStream = nil;
}
if (self.fileStream != nil) {
[self.fileStream close];
self.fileStream = nil;
}
[self envioDetenido:estado];
}
- (void)continuaEnvio
{
double delayInSeconds = 12.0;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
NSLog(#"After Delay code");
if ([self.networkStream streamStatus] != NSStreamStatusOpen) {
PutController *ftp = [[PutController alloc] init];
ftp.delegate = self;
_currentBytesEnviados = _totalBytesSend;//_currentDatos.length;
NSLog(#"Current total bytes ** %i", _currentBytesEnviados);
[ftp enviar:_currentDatos pathArchivo:_currentPathArchivos bytesEnviados:_currentBytesEnviados];
self.ftpController = ftp;
}
});
}
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
// An NSStream delegate callback that's called when events happen on our
// network stream.
{
#pragma unused(aStream)
assert(aStream == self.networkStream);
switch (eventCode) {
case NSStreamEventOpenCompleted: {
[self iniciarEnvio:#"Abriendo conexion"];
} break;
case NSStreamEventHasBytesAvailable: {
assert(NO); // should never happen for the output stream
} break;
case NSStreamEventHasSpaceAvailable: {
// If we don't have any data buffered, go read the next chunk of data.
if (self.bufferOffset == self.bufferLimit) {
NSInteger bytesRead;
bytesRead = [self.fileStream read:self.buffer maxLength:kSendBufferSize];
if (bytesRead == -1) {
[self detenerEnvio:#"Error al leer archivo."];
} else if (bytesRead == 0) {
[self detenerEnvio:nil];
break;
} else {
self.bufferOffset = 0;
self.bufferLimit = bytesRead;
}
}
// If we're not out of data completely, send the next chunk.
if (self.bufferOffset != self.bufferLimit) {
NSInteger bytesWritten;
bytesWritten = [self.networkStream write:&self.buffer[self.bufferOffset] maxLength:self.bufferLimit - self.bufferOffset];
assert(bytesWritten != 0);
if (bytesWritten == -1) {
[self detenerEnvio:#"Error al escribir."];
} else {
self.bufferOffset += bytesWritten;
_totalBytesSend += bytesWritten;
[self actualizaEnvio:bytesWritten];
}
}
} break;
case NSStreamEventErrorOccurred: {
//**** Here is where im trying to resume the upload *****
[self detenerEnvio:#"Error al abrir el stream."];
[self continuaEnvio];
} break;
case NSStreamEventEndEncountered: {
// ignore
} break;
default: {
assert(NO);
} break;
}
}
Thanks in advance!

Implementing SimpleFTPSample in swift

I am trying to convert an Objective-C app to swift.
I am reaching the part where I need to send a file through FTP to a distant server. I was able to to that in Objective-C but only because I had the SimpleFTPSample project that apple made to help the developers.
Right now I have almost complete the conversion between the two language but I am stuck.
I need to convert that code (from SimpleFTPSample+personal):
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
// An NSStream delegate callback that's called when events happen on our
// network stream.
{
#pragma unused(aStream)
assert(aStream == self.networkStream);
switch (eventCode) {
case NSStreamEventOpenCompleted: {
[self updateStatus:#"Opened connection"];
} break;
case NSStreamEventHasBytesAvailable: {
assert(NO); // should never happen for the output stream
} break;
case NSStreamEventHasSpaceAvailable: {
[self updateStatus:#"Sending"];
// If we don't have any data buffered, go read the next chunk of data.
if (self.bufferOffset == self.bufferLimit) {
NSInteger bytesRead;
bytesRead = [self.fileStream read:self.buffer maxLength:kSendBufferSize];
if (bytesRead == -1) {
[self stopSendWithStatus:#"File read error"];
} else if (bytesRead == 0) {
[self stopSendWithStatus:nil];
} else {
self.bufferOffset = 0;
self.bufferLimit = bytesRead;
}
}
// If we're not out of data completely, send the next chunk.
if (self.bufferOffset != self.bufferLimit) {
NSInteger bytesWritten;
bytesWritten = [self.networkStream write:&self.buffer[self.bufferOffset] maxLength:self.bufferLimit - self.bufferOffset];
assert(bytesWritten != 0);
if (bytesWritten == -1) {
[self stopSendWithStatus:#"Network write error"];
} else {
self.bufferOffset += bytesWritten;
}
}
} break;
case NSStreamEventErrorOccurred: {
[self stopSendWithStatus:#"Stream open error"];
} break;
case NSStreamEventEndEncountered: {
// ignore
} break;
default: {
assert(NO);
} break;
}
}
For now I managed to do that :
// An NSStream delegate callback that's called when events happen on our
// network stream.
func stream(theStream: NSStream!, handleEvent streamEvent: NSStreamEvent) {
switch (streamEvent) {
case NSStreamEvent.OpenCompleted:
println("Opened connection")
case NSStreamEvent.HasBytesAvailable:
println("Not suposed to happend")
case NSStreamEvent.HasSpaceAvailable:
println("Sending")
// If we don't have any data buffered, go read the next chunk of data.
if self.bufferOffset == self.bufferLimit {
var bytesRead: Int
bytesRead = self.fileStream.read(self.buffer, maxLength: 32768)
if bytesRead == -1 { self.stopSendWithStatus("File read error") }
else if bytesRead == 0 { self.stopSendWithStatus(nil) }
else {
self.bufferOffset = 0
self.bufferLimit = size_t(bytesRead)
}
}
// If we're not out of data completely, send the next chunk.
if self.bufferOffset != self.bufferLimit {
var bytesWritten: Int
bytesWritten = self.networkStream.write(&self.buffer[self.bufferOffset], maxLength: self.bufferLimit - self.bufferOffset)
if bytesWritten == -1 { self.stopSendWithStatus("Network write error") }
else { self.bufferOffset += size_t(bytesWritten) }
}
case NSStreamEvent.ErrorOccurred:
self.stopSendWithStatus("Stream open error")
case NSStreamEvent.EndEncountered:
println("ignore")
default:
println("default")
}
}
The kind of the used variables is :
var isSending = Bool()
var networkStream: NSOutputStream! = NSOutputStream()
var fileStream: NSInputStream! = NSInputStream()
var buffer: CConstPointer<UInt8>
var bufferOffset = size_t()
var bufferLimit = size_t()
I am stuck for the if self.bufferOffset != self.bufferLimit part.
Apparently &self.buffer[self.bufferOffset] is not correct (does not have a member name subscript), as well as self.bufferLimit - self.bufferOffset (could not find an overload '-' that accepts the supplied arguments)
To be honest I am not even sure to get what &self.buffer[self.bufferOffset] means. (not the variable but the notation.
So if someone has an idea on how to fixe that, he will be very welcomed !
You can find the SimpleFTPSample project here.
Sorry if my english is not perfect.
Can't you just compile SimpleFTP into a framework and use its methods directly from swift? No need to rewrite everything, Xcode does that for you. I use that for many custom libraries and it works like a charm. Just add target, and put in the required frameworks, include the framework and you're all set!
Here is my plagiarism of apple's SimpleFTPExample to solve my problem of uploading a csv file from an iOS app to a ftp server.
I took the PutController objective-c file, cut lots and lots (too much?) out of it an included it into my swift application.
I modified the parameters passed to the main PutController function, to pass in the data I wanted to send, the URL it has to go to and the username and password to get onto the server.
The cut down PutController.m
#import "PutController.h"
#include <CFNetwork/CFNetwork.h>
enum {
kSendBufferSize = 32768
};
#interface PutController () <NSStreamDelegate>
#property (nonatomic, strong, readwrite) NSOutputStream * networkStream;
#property (nonatomic, strong, readwrite) NSInputStream * fileStream;
#property (nonatomic, assign, readonly ) uint8_t * buffer;
#property (nonatomic, assign, readwrite) size_t bufferOffset;
#property (nonatomic, assign, readwrite) size_t bufferLimit;
#end
#implementation PutController
{
uint8_t _buffer[kSendBufferSize];
}
// Because buffer is declared as an array, you have to use a custom getter.
// A synthesised getter doesn't compile.
- (uint8_t *)buffer
{
return self->_buffer;
}
- (void)startSend:(NSData *)dataToUpload withURL:(NSURL *)toURL withUsername:(NSString *)username andPassword:(NSString *)password
{
printf(__FUNCTION__);
self.fileStream = [NSInputStream inputStreamWithData:dataToUpload];
[self.fileStream open];
// Open a CFFTPStream for the URL.
self.networkStream = CFBridgingRelease(
CFWriteStreamCreateWithFTPURL(NULL, (__bridge CFURLRef) toURL)
);
[self.networkStream setProperty:username forKey:(id)kCFStreamPropertyFTPUserName];
[self.networkStream setProperty:password forKey:(id)kCFStreamPropertyFTPPassword];
self.networkStream.delegate = self;
[self.networkStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[self.networkStream open];
}
- (void)stopSendWithStatus:(NSString *)statusString
{
printf(__FUNCTION__);
if (self.networkStream != nil) {
[self.networkStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
self.networkStream.delegate = nil;
[self.networkStream close];
self.networkStream = nil;
}
if (self.fileStream != nil) {
[self.fileStream close];
self.fileStream = nil;
}
}
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
// An NSStream delegate callback that's called when events happen on our
// network stream.
{
printf(__FUNCTION__);
switch (eventCode) {
case NSStreamEventOpenCompleted: {
printf("Opened connection");
} break;
case NSStreamEventHasBytesAvailable: {
printf("should never happen for the output stream");
} break;
case NSStreamEventHasSpaceAvailable: {
printf("Sending");
// If we don't have any data buffered, go read the next chunk of data.
if (self.bufferOffset == self.bufferLimit) {
NSInteger bytesRead;
bytesRead = [self.fileStream read:self.buffer maxLength:kSendBufferSize];
if (bytesRead == -1) {
[self stopSendWithStatus:#"File read error"];
} else if (bytesRead == 0) {
[self stopSendWithStatus:nil];
} else {
self.bufferOffset = 0;
self.bufferLimit = bytesRead;
}
}
// If we're not out of data completely, send the next chunk.
if (self.bufferOffset != self.bufferLimit) {
NSInteger bytesWritten;
bytesWritten = [self.networkStream write:&self.buffer[self.bufferOffset] maxLength:self.bufferLimit - self.bufferOffset];
assert(bytesWritten != 0);
if (bytesWritten == -1) {
[self stopSendWithStatus:#"Network write error"];
} else {
self.bufferOffset += bytesWritten;
}
}
} break;
case NSStreamEventErrorOccurred: {
[self stopSendWithStatus:#"Stream open error"];
} break;
case NSStreamEventEndEncountered: {
// ignore
} break;
default: {
assert(NO);
} break;
}
}
#end
Then the PutController.h
#import <UIKit/UIKit.h>
#interface PutController : NSObject
- (void)startSend:(NSData *)dataToUpload withURL:(NSURL *)toURL withUsername:(NSString *)username andPassword:(NSString *)password;
#end
This is the bridging file, that is project wide, to allow the swift application to pick up the objective-C header files. The objective-C code detail can then be mostly ignored. It really is one line.
// PlantRoomChecks-Bridging-Header.h
//
// Use this file to import your target's public headers that you would like to expose to Swift.
//
#import "PutController.h"
This is my project file that call the PutController. I have cut it to show just the relevant parts.
// Showing that I am not including any networking libraries
import UIKit
import CoreGraphics
class GraphVC: UIViewController {
var sendFile : PutController = PutController()
let username = "arthur_dent"
let password = "six_times_seven"
func saveData(){
var filename = "ftp://www.domain.co.uk/subdirectory/datafile"
// Converting the messing filename into one that can be used as a URL
let convertedStringForURL = filename.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding)
let uploadUrl = NSURL(string: convertedStringForURL!)
Let dataForFile : NSData = dataFromElseWhere
let dataToUpload = dataForFile.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
// USE THE OBJECTIVE-C VARIABLE
sendFile.startSend(dataToUpload, withURL: uploadUrl, withUsername: username, andPassword: password)
}

Close connection when NSOutputStream has finished

How can a connection be closed when the NSOutputStream has finished sending data?
After searching around i have found that the event NSStreamEventEndEncountered is only called if the server drops the connection. not if the OutputStream has finished the data to send.
StreamStatus is Always returning 0 (connection closed) or 2 (connection open) but never 4 (writing data).
since both methods mentioned above are not telling me enough about the write process i am not able to find a way do determine if the Stream is still writing or if it has finished and i can close the connection now.
After 5 days of googleling and trying i am totally out of ideas... Any help appreciated. Thanks
EDIT ADDED CODE AS REQUESTED:
- (void)startSend:(NSString *)filePath
{
BOOL success;
NSURL * url;
assert(filePath != nil);
assert([[NSFileManager defaultManager] fileExistsAtPath:filePath]);
assert( [filePath.pathExtension isEqual:#"png"] || [filePath.pathExtension isEqual:#"jpg"] );
assert(self.networkStream == nil); // don't tap send twice in a row!
assert(self.fileStream == nil); // ditto
// First get and check the URL.
...
....
.....
// If the URL is bogus, let the user know. Otherwise kick off the connection.
...
....
.....
if ( ! success) {
self.statusLabel.text = #"Invalid URL";
} else {
// Open a stream for the file we're going to send. We do not open this stream;
// NSURLConnection will do it for us.
self.fileStream = [NSInputStream inputStreamWithFileAtPath:filePath];
assert(self.fileStream != nil);
[self.fileStream open];
// Open a CFFTPStream for the URL.
self.networkStream = CFBridgingRelease(
CFWriteStreamCreateWithFTPURL(NULL, (__bridge CFURLRef) url)
);
assert(self.networkStream != nil);
if ([self.usernameText.text length] != 0) {
success = [self.networkStream setProperty:self.usernameText.text forKey:(id)kCFStreamPropertyFTPUserName];
assert(success);
success = [self.networkStream setProperty:self.passwordText.text forKey:(id)kCFStreamPropertyFTPPassword];
assert(success);
}
self.networkStream.delegate = self;
[self.networkStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
///////******** LINE ADDED BY ME TO DISONNECT FROM FTP AFTER CLOSING CONNECTION *********////////////
[self.networkStream setProperty:(id)kCFBooleanFalse forKey:(id)kCFStreamPropertyFTPAttemptPersistentConnection];
///////******** END LINE ADDED BY ME *********////////////
[self.networkStream open];
// Tell the UI we're sending.
[self sendDidStart];
}
}
- (void)stopSendWithStatus:(NSString *)statusString
{
if (self.networkStream != nil) {
[self.networkStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
self.networkStream.delegate = nil;
[self.networkStream close];
self.networkStream = nil;
}
if (self.fileStream != nil) {
[self.fileStream close];
self.fileStream = nil;
}
[self sendDidStopWithStatus:statusString];
}
- (void)stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
// An NSStream delegate callback that's called when events happen on our
// network stream.
{
#pragma unused(aStream)
assert(aStream == self.networkStream);
switch (eventCode) {
case NSStreamEventOpenCompleted: {
[self updateStatus:#"Opened connection"];
} break;
case NSStreamEventHasBytesAvailable: {
assert(NO); // should never happen for the output stream
} break;
case NSStreamEventHasSpaceAvailable: {
[self updateStatus:#"Sending"];
// If we don't have any data buffered, go read the next chunk of data.
if (self.bufferOffset == self.bufferLimit) {
NSInteger bytesRead;
bytesRead = [self.fileStream read:self.buffer maxLength:kSendBufferSize];
if (bytesRead == -1) {
[self stopSendWithStatus:#"File read error"];
} else if (bytesRead == 0) {
[self stopSendWithStatus:nil];
} else {
self.bufferOffset = 0;
self.bufferLimit = bytesRead;
}
}
// If we're not out of data completely, send the next chunk.
if (self.bufferOffset != self.bufferLimit) {
NSInteger bytesWritten;
bytesWritten = [self.networkStream write:&self.buffer[self.bufferOffset] maxLength:self.bufferLimit - self.bufferOffset];
assert(bytesWritten != 0);
if (bytesWritten == -1) {
[self stopSendWithStatus:#"Network write error"];
} else {
self.bufferOffset += bytesWritten;
}
}
} break;
case NSStreamEventErrorOccurred: {
[self stopSendWithStatus:#"Stream open error"];
} break;
case NSStreamEventEndEncountered: {
// FOR WHATEVER REASON THIS IS NEVER CALLED!!!!
} break;
default: {
assert(NO);
} break;
}
}
There can be two interpretations to your question. If what you are asking is "I have a NSOutputStream and I'm finished writing to it how do I signal this?" then the answer is as simple as call the close method on it.
Alternately, If what you are really saying is "I have a NSInputStream and I want to know when I've reached the end-of-stream" then you can look at hasBytesAvailable or streamStatus == NSStreamStatusAtEnd.
For your information, to actually get the status NSStreamStatusWriting you would need to be calling the streamStatus method from another thread while this thread is calling write:maxLength:.
--- Edit: Code Suggestion
The reason you would never get notified is that an output stream is never finished (unless it's a fixed size stream, which an FTP stream is not). It's the input stream that gets "finished" at which point you can close your output stream. That's the answer to your original question.
As a further suggestion, I would skip run loop scheduling and the "event processing" except for handling errors on the output stream. Then I would put the read/write code into a NSOperation subclass and send it off into a NSOperationQueue. By keeping a reference to the NSOperations in that queue you would be able to cancel them easily and even show a progress bar by adding a percentComplete property. I've tested the code below and it works. Replace my memory output stream with your FTP output stream. You will notice that I have skipped the validations, which you should keep of course. They should probably be done outside the NSOperation to make it easier to query the user.
#interface NSSendFileOperation : NSOperation<NSStreamDelegate> {
NSInputStream *_inputStream;
NSOutputStream *_outputStream;
uint8_t *_buffer;
}
#property (copy) NSString* sourceFilePath;
#property (copy) NSString* targetFilePath;
#property (copy) NSString* username;
#property (copy) NSString* password;
#end
#implementation NSSendFileOperation
- (void) main
{
static int kBufferSize = 4096;
_inputStream = [NSInputStream inputStreamWithFileAtPath:self.sourceFilePath];
_outputStream = [NSOutputStream outputStreamToMemory];
_outputStream.delegate = self;
[_inputStream open];
[_outputStream open];
_buffer = calloc(1, kBufferSize);
while (_inputStream.hasBytesAvailable) {
NSInteger bytesRead = [_inputStream read:_buffer maxLength:kBufferSize];
if (bytesRead > 0) {
[_outputStream write:_buffer maxLength:bytesRead];
NSLog(#"Wrote %ld bytes to output stream",bytesRead);
}
}
NSData *outputData = [_outputStream propertyForKey:NSStreamDataWrittenToMemoryStreamKey];
NSLog(#"Wrote a total of %lu bytes to output stream.", outputData.length);
free(_buffer);
_buffer = NULL;
[_outputStream close];
[_inputStream close];
}
- (void) stream:(NSStream *)aStream handleEvent:(NSStreamEvent)eventCode
{
// Handle output stream errors such as disconnections here
}
#end
int main (int argc, const char * argv[])
{
#autoreleasepool {
NSOperationQueue *sendQueue = [[NSOperationQueue alloc] init];
NSSendFileOperation *sendOp = [[NSSendFileOperation alloc] init];
sendOp.username = #"test";
sendOp.password = #"test";
sendOp.sourceFilePath = #"/Users/eric/bin/data/english-words.txt";
sendOp.targetFilePath = #"/Users/eric/Desktop/english-words.txt";
[sendQueue addOperation:sendOp];
[sendQueue waitUntilAllOperationsAreFinished];
}
return 0;
}

How to fade an NSSound object

I've written a cheap & cheerful sound board in for my Mac, and I play the various sounds with NSSound like this:
-(void)play:(NSSound *)soundEffect:(BOOL)stopIfPlaying {
BOOL wasPlaying = FALSE;
if([nowPlaying isPlaying]) {
[nowPlaying stop];
wasPlaying = TRUE;
}
if(soundEffect != nowPlaying)
{
[soundEffect play];
nowPlaying = soundEffect;
} else if(soundEffect == nowPlaying && ![nowPlaying isPlaying] && !wasPlaying) {
[nowPlaying play];
}
}
Rather than just stop it dead, I'd like it to fade out over a couple of seconds or so.
This is the final version of the method:
-(void)play:(NSSound *)soundEffect:(BOOL)stopIfPlaying {
BOOL wasPlaying = FALSE;
if([nowPlaying isPlaying]) {
struct timespec ts;
ts.tv_sec = 0;
ts.tv_nsec = 25000000;
// If the sound effect is the same, fade it out.
if(soundEffect == nowPlaying)
{
for(int i = 1; i < 30; ++i)
{
[nowPlaying setVolume: (1.0 / i )];
nanosleep(&ts, &ts);
}
}
[nowPlaying stop];
[nowPlaying setVolume:1];
wasPlaying = TRUE;
}
if(soundEffect != nowPlaying)
{
[soundEffect play];
nowPlaying = soundEffect;
} else if(soundEffect == nowPlaying && ![nowPlaying isPlaying] && !wasPlaying) {
[nowPlaying play];
}
}
So it only fades out if I pass the same sound in (ie, click the same button), also, I went for nanosleep rather than sleep, as that on has a granularity of 1 second.
I struggled for a while trying to work out why my 200 millisecond delay didn't seem to have any effect, but then 200 NANOseconds isn't really that long is it :-)
I would use NSTimer to avoid blocking the main thread.
Something like this perhaps? You probably want a more linear dropoff, but the basic idea is make a loop and sleep the period of time till the next update.
if([nowPlaying isPlaying]) {
for(int i = 1; i < 100; ++i)
{
[nowPlaying setVolume: (1.0 / i)];
Sleep(20);
}
[nowPlaying stop];
wasPlaying = TRUE;
}