【发布时间】:2017-03-17 22:09:38
【问题描述】:
我想在Alamofire 上一次只处理一个请求 - 这意味着当第一个请求得到响应时,它将处理第二个请求,依此类推。
如何做到这一点?
【问题讨论】:
-
在第一个请求的成功块中,调用第二个请求,依此类推
-
你了解客观的 C 代码吗?
标签: ios swift request alamofire synchronous
我想在Alamofire 上一次只处理一个请求 - 这意味着当第一个请求得到响应时,它将处理第二个请求,依此类推。
如何做到这一点?
【问题讨论】:
标签: ios swift request alamofire synchronous
基本上你可以从几种方法中选择一种:
使用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); }
我猜最简单的方法是使用GCD
【讨论】:
您可以创建一个调度队列或 nsoprations 以及您的 alamofire 任务。记得做一个同步队列
此链接可能对您有所帮助 http://nshipster.com/nsoperation/
【讨论】: