iOS, NSURLConnection: Delegate Callbacks on Different Thread?

后端 未结 4 1424
借酒劲吻你
借酒劲吻你 2020-12-28 10:20

How can I get NSURLConnection to call it\'s delegate methods from a different thread instead of the main thread. I\'m trying to mess around with the scheduleInRunLoop:forMod

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-28 11:09

    There are several options:

    1. In your implementation of the delegate methods, make use of dispatch_async.
    2. Start the schedule the connection on a background thread.

    You can do the latter like this:

    // all the setup comes here
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSRunLoop *loop = [NSRunLoop currentRunLoop];
        [connection scheduleInRunLoop:loop forMode:NSRunLoopCommonModes];
        [loop run]; // make sure that you have a running run-loop.
    });
    

    If you want a guarantee on which thread you're running, replace the call to dispatch_get_global_queue() appropriately.

提交回复
热议问题