这是一个完全符合您所说的教程。虽然它更侧重于音频流,但原理完全相同(即在产生工作线程、让它与父线程对话等方面)。
这个想法很简单..您创建一个新线程并让它处理流工作,然后您使用属于您刚刚创建的线程的运行循环调度流阅读器。流将具有回调,当某些事件发生时将触发(即您获得一些数据,连接超时等)。在回调方法中,您可以警告或与主线程(这是处理 UI 的线程)通信.
这里有一些代码可以为你指明正确的方向,但是如果你从上面的教程下载代码并按照.. 你会得到它:
// create a new thread
internalThread =
[[NSThread alloc]
initWithTarget:self
selector:@selector(startInternal)
object:nil];
[internalThread start];
// creating a stream inside the 'startInternal' thread*
stream = CFReadStreamCreateForHTTPRequest(NULL, message);
// open stream
CFReadStreamOpen(stream)
// set callback functions
// ie say: if there are bites available in the stream, fire a callback etc
CFStreamClientContext context = {0, self, NULL, NULL, NULL};
CFReadStreamSetClient(
stream,
kCFStreamEventHasBytesAvailable | kCFStreamEventErrorOccurred | kCFStreamEventEndEncountered,
ASReadStreamCallBack,
&context);
// schedule stream in current thread runloop, so that we DON'T block the mainthread
CFReadStreamScheduleWithRunLoop(stream, CFRunLoopGetCurrent(), kCFRunLoopCommonModes);
// create the callback function to handle reading from stream
// NOTE: see where else in the code this function is named (ie CFReadStreamSetClient)
static void ASReadStreamCallBack
(
CFReadStreamRef aStream,
CFStreamEventType eventType,
void* inClientInfo
)
{
//handle events you registered above
// ie
if (eventType == kCFStreamEventHasBytesAvailable) {
// handle network data here..
..
// if something goes wrong, create an alert and run it through the main thread:
UIAlertView *alert = [
[[UIAlertView alloc]
initWithTitle:title
message:message
delegate:self
cancelButtonTitle:NSLocalizedString(@"OK", @"")
otherButtonTitles: nil]
autorelease];
[alert
performSelector:@selector(show)
onThread:[NSThread mainThread]
withObject:nil
waitUntilDone:NO];
}
}