【问题标题】:Processing only one request at a time in Alamofire?在 Alamofire 中一次只处理一个请求?
【发布时间】:2017-03-17 22:09:38
【问题描述】:

我想在Alamofire 上一次只处理一个请求 - 这意味着当第一个请求得到响应时,它将处理第二个请求,依此类推。

如何做到这一点?

【问题讨论】:

  • 在第一个请求的成功块中,调用第二个请求,依此类推
  • 你了解客观的 C 代码吗?

标签: ios swift request alamofire synchronous


【解决方案1】:

基本上你可以从几种方法中选择一种:

  1. 使用NSOperationQueue - 使用maxConcurrentOperationCount = 1 创建队列,然后简单地将任务添加到队列中。示例:

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

    如果你需要取消所有任务 - operationQueue.cancelAllOperations()

  2. 使用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. GCDDISPATCH_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 - 简单示例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. 使用某种NestedChainRequests - 创建一些类来逐一处理请求,example

  2. 使用PromiseKit (link) 与Alamofire (link)

我猜最简单的方法是使用GCD

【讨论】:

    【解决方案2】:

    您可以创建一个调度队列或 nsoprations 以及您的 alamofire 任务。记得做一个同步队列

    此链接可能对您有所帮助 http://nshipster.com/nsoperation/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-07-12
      • 2017-08-10
      • 2019-05-11
      • 2020-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多