ios - 在 Alamofire 中一次只处理一个请求?

标签 ios swift request alamofire synchronous

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

如何实现?

最佳答案

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

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

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

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

  2. 使用信号量

    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

关于ios - 在 Alamofire 中一次只处理一个请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40416504/

相关文章:

iOS - Interface Builder - 自动布局两个标签

swift - 将 Alamofire 请求数据保存到变量中

ios - 如何更改导航栏上 "back"按钮的标题

json - 解码对象,其中一个对象是JSON字符串

ios - UITableView 多个 insertSections 到同一个索引

ios - 如何从 plist iOS 读取数组

controller - 如何从 Controller 中的 header 获取 JWT token

java - 服务器遇到意外情况,无法满足请求。 HTTP 500

ios - Xamarin/iOS SharedAccessoryManager.ShowBluetoothAccessoryPicker 失败

iphone - UITableViewCell 设置选中图片