質問

Currently when i open an NSInputStream (for example) I can set it up to get an event indicating that it has opened completely. But if it fails, there is no event at all. I never get told that the opening failed to complete. I can poll while it is attempting to open, but then I have to tie up a thread for potentially a lengthy period of time.

What I want to do is write efficient code that waits for either the stream to open or fail to open. Is there any such way using NSStream et al?

I also thought of creating an event that I could wait on for a set period of time. If the connection succeeded, the event would signal and pop me out of my wait state. If the timeout occurred, I could test the status and see if it failed or go back into the wait state again. But of course this is plan B, not eloquent and not efficient. And looking through the CocoaTouch documentation doesn't make clear at all how to create such a signal that I can wait on with a timeout.

Any help would be appreciated.

役に立ちましたか?

解決

There is an event that occurs when a NSStream fails to open: NSStreamEventErrorOccurred. Perhaps the problem you are encountering is that the TCP/IP timeout can be very long. So if a connection to a host is going to fail it may be 30 seconds before you get this event.

You could start an NSTimer at the same time that open the stream for some shorter interval, but then you run into the problem of what that interval should be?

It is often better to leave the option to cancel the connection in the hands of the user, unless the TCP/IP timeout occurs.

What I have done in a number of projects is popped a custom modal view with an activity indicator and a cancel button after about 1 second. Many connections on local networks will complete before this time and the user will not be bothered by the popup. For slower connections this allows the user to decide how long they are willing to wait. You can even update the message in the modal view after some longer period of time to say that it is taking longer to connect than usual so they know the program is aware that they are waiting!

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top