是的,这是预期的行为。一种解决方案是将请求包装在自定义异步NSOperation
子类中,然后使用maxConcurrentOperationCount
操作队列的来控制并发请求的数量,而不是HTTPMaximumConnectionsPerHost
参数。
原始的AFNetworking很好地完成了将请求包装到操作中的工作,这变得微不足道。但是AFNetworking的NSURLSession
实现从来没有这样做,Alamofire也没有。
您可以轻松地将其包装Request
在NSOperation
子类中。例如:
class NetworkOperation: AsynchronousOperation {
private let urlString: String
private var networkOperationCompletionHandler: ((_ responseObject: Any?, _ error: Error?) -> Void)?
weak var request: Alamofire.Request?
init(urlString: String, networkOperationCompletionHandler: ((_ responseObject: Any?, _ error: Error?) -> Void)? = nil) {
self.urlString = urlString
self.networkOperationCompletionHandler = networkOperationCompletionHandler
super.init()
}
override func main() {
request = Alamofire.request(urlString, method: .get, parameters: ["foo" : "bar"])
.responseJSON { response in
self.networkOperationCompletionHandler?(response.result.value, response.result.error)
self.networkOperationCompletionHandler = nil
self.completeOperation()
}
}
override func cancel() {
request?.cancel()
super.cancel()
}
}
然后,当我要发起50个请求时,我将执行以下操作:
let queue = OperationQueue()
queue.maxConcurrentOperationCount = 2
for i in 0 ..< 50 {
let operation = NetworkOperation(urlString: "http://example.com/request.php?value=\(i)") { responseObject, error in
guard let responseObject = responseObject else {
print("failed: \(error?.localizedDescription ?? "Unknown error")")
return
}
print("responseObject=\(responseObject)")
}
queue.addOperation(operation)
}
这样,这些请求将受到的约束maxConcurrentOperationCount
,我们不必担心任何请求都会超时。
这是一个示例AsynchronousOperation
基类,它负责与异步/并行NSOperation
子类关联的KVN :
import Foundation
public class AsynchronousOperation : Operation {
private let stateLock = NSLock()
private var _executing: Bool = false
override private(set) public var isExecuting: Bool {
get {
return stateLock.withCriticalScope { _executing }
}
set {
willChangeValue(forKey: "isExecuting")
stateLock.withCriticalScope { _executing = newValue }
didChangeValue(forKey: "isExecuting")
}
}
private var _finished: Bool = false
override private(set) public var isFinished: Bool {
get {
return stateLock.withCriticalScope { _finished }
}
set {
willChangeValue(forKey: "isFinished")
stateLock.withCriticalScope { _finished = newValue }
didChangeValue(forKey: "isFinished")
}
}
public func completeOperation() {
if isExecuting {
isExecuting = false
}
if !isFinished {
isFinished = true
}
}
override public func start() {
if isCancelled {
isFinished = true
return
}
isExecuting = true
main()
}
override public func main() {
fatalError("subclasses must override `main`")
}
}
import Foundation
extension NSLocking {
func withCriticalScope<T>(block: () throws -> T) rethrows -> T {
lock()
defer { unlock() }
return try block()
}
}
有此模式的其它可能的变化,只是保证你(一)收益true
的asynchronous
; (b)按照《并发编程指南:操作队列》中的“配置并发执行操作”部分所述,发布必要的KVNisFinished
和isExecuting
KVN 。
, not
timeoutIntervalForRequest`?