4

I'm currently trying to run my whole network stuff in a background thread, as it currently blocks the main thread, when the server is not reachable (i.e.).

I'm currently creating the network connection through the following code. Is there a simple way to run this in a new background thread?

An how can I throw back the received message to the main thread? An how can I send messages through the background thread?

CFReadStreamRef readStream;
CFWriteStreamRef writeStream;
CFStreamCreatePairWithSocketToHost(NULL, (__bridge CFStringRef)ipAdress, port, &readStream, &writeStream);
inputStream = (__bridge NSInputStream *)readStream;
outputStream = (__bridge NSOutputStream *)writeStream;
[inputStream setDelegate:self];
[outputStream setDelegate:self];
[inputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
[outputStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];

[inputStream open];
[outputStream open];
6
  • Since you're using a runloop and not polling the streams, is there a particular problem you think you can solve by pushing this onto a background thread?
    – 一二三
    Mar 26, 2013 at 8:07
  • Hi, i'm not sure, as i'm not really into threading and co. in objective-c. I'm open to any other suggestions. Are there any good tutorials out there how to solve this problem? Thanks!
    – Lukas
    Mar 26, 2013 at 8:10
  • What is the problem? Why do you want to use a separate thread?
    – 一二三
    Mar 26, 2013 at 8:15
  • The problem is that my connection blocks the main thread for about 30 secs. if the server is not available. I used apple's reachability class to check the connection before connection, but i think this is not a nice approach.
    – Lukas
    Mar 26, 2013 at 8:18
  • i just updated my answer to make it more readable.. lemme know if that's what you're looking for.
    – abbood
    Mar 26, 2013 at 9:03

1 Answer 1

5

here is a tutorial that does exactly what you're talking about. although it focuses more on audio streaming, but the principles are exactly the same (ie in terms of spawning a worker thread, having it talk with the parent thread etc etc).

the idea is simple.. you create a new thread and have it handle the streaming work, and then you schedule the stream reader with the run loop that belongs to the thread you just created. The stream will have callbacks that will be fired when ceratain events happen (ie you get some data, the connect times out etc).. in the callback methods you can alert or communicate with the mainthread (which is the thread that handles the UI).

Here is some code to point you in the right direction, but if you download the code from the above tutorial and follow through.. you'll get it:

// 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];        
    }          
}
1
  • Thank's for your help, but was not exactly what i was searching for. I finaly solved the problem by following the following guid. benincosa.com/blog/?p=449 Anyway thank#s for your afford!
    – Lukas
    Mar 26, 2013 at 11:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.