anik_s
anik_s

Reputation: 263

Processing only one request at a time in Alamofire?

I want to process only one request at a time that on Alamofire - meaning when response come for first request it will process the second request and so on.

How to achieve this?

Upvotes: 1

Views: 948

Answers (2)

hbk
hbk

Reputation: 11184

Basically u can select one from the few approaches:

  1. Use NSOperationQueue - create queue with maxConcurrentOperationCount = 1, and simply add task in to queue. Sample:

    let operationQueue:NSOperationQueue = NSOperationQueue()
    operationQueue.name = "name.com"
    operationQueue.maxConcurrentOperationCount = 1
    operationQueue.addOperationWithBlock {  
        //do staff here
    }
    

    if u need to cancel all task - operationQueue.cancelAllOperations()

  2. Use semaphore

    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0)
    
    request.execute = {
        //do staff here    
        dispatch_semaphore_signal(sema)
    }
    
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER) //or 
    dispatch_semaphore_wait(semaphore, dispatch_time( DISPATCH_TIME_NOW, Int64(60 * Double(NSEC_PER_SEC)))) //if u need some timeout
    dispatch_release(semaphore)
    
  3. GCD and DISPATCH_QUEUE_SERIAL

    let serialQueue = dispatch_queue_create("name.com", DISPATCH_QUEUE_SERIAL)
    
    func test(interval: NSTimeInterval) {
          NSThread.sleepForTimeInterval(interval)
          print("\(interval)")
    }
    dispatch_async(serialQueue, {
        test(13)
    })
    dispatch_async(serialQueue, {
        test(1)
     })
    dispatch_async(serialQueue, {
         test(5)
    })
    
  4. Mutex - simple sample from here :

pthread_mutex_t mutex;
void MyInitFunction()
{
    pthread_mutex_init(&mutex, NULL);
}

void MyLockingFunction()
{
    pthread_mutex_lock(&mutex);
    // Do work.
    pthread_mutex_unlock(&mutex);
}
  1. Use some kind of NestedChainRequests - make some class that will handle request one-by-one, example

  2. Use PromiseKit (link) vs Alamofire (link)

The simplest approach I guess is to use GCD

Upvotes: 3

Jay Gajjar
Jay Gajjar

Reputation: 2741

You can create a dispatch queue or nsoprations and your alamofire task to it. Remember make a synchronous queue

This link might help you http://nshipster.com/nsoperation/

Upvotes: 1

Related Questions