我想在Alamofire
上一次只处理一个请求 - 这意味着当第一个请求响应时,它将处理第二个请求,依此类推。
如何实现这一目标?
答案 0 :(得分:2)
基本上你可以从几种方法中选择一种:
使用NSOperationQueue
- 使用maxConcurrentOperationCount = 1
创建队列,只需将任务添加到队列中。样品:
let operationQueue:NSOperationQueue = NSOperationQueue()
operationQueue.name = "name.com"
operationQueue.maxConcurrentOperationCount = 1
operationQueue.addOperationWithBlock {
//do staff here
}
如果您需要取消所有任务 - operationQueue.cancelAllOperations()
使用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)
GCD
和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)
})
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 :(得分:0)
您可以创建一个调度队列或nsoprations以及您的alamofire任务。记住创建一个同步队列
此链接可能对您有所帮助 http://nshipster.com/nsoperation/