How do I start an Asynchronous NSURLConnection inside an NSOperation?

前端 未结 3 554
南笙
南笙 2021-01-06 06:27

I want to do an Asynchrous NSURLConnection inside of an NSOperation on a background thread. it is because I\'m doing some very expensive operations on the data as they come

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-06 07:19

    I know this post is over a year old, but I wanted to add some suggestions for people who may run the same problem trying to create own async network operation. You need to add runloop to operation that runs in background and you should stop it when the operations has finished.

    There actually 2 simple options:

    Option 1 - using NSRunLoop

    NSPort *port        = [NSPort port];
    NSRunLoop *runLoop  = [NSRunLoop currentRunLoop];
    [runLoop addPort:port forMode:NSDefaultRunLoopMode];
    [self.connection scheduleInRunLoop:runLoop forMode:NSDefaultRunLoopMode];
    [self.connection start];
    [runLoop run];
    

    and you need to stop when the operation is finished:

    NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
    NSDate *date       = [NSDate distantFuture];
    while (!runLoopIsStopped && [runLoop runMode:NSDefaultRunLoopMode beforeDate:date]);
    

    Option 2 - using CF

    You need to add

    CFRunLoopRun();
    

    when you start operation

    and call

    CFRunLoopStop(CFRunLoopGetCurrent());
    

    when you finish operation.

    Read the following post: CFRunLoopRun() vs [NSRunLoop run]

提交回复
热议问题