我的测试应用程序出现了一些奇怪的行为.我同时向同一台服务器发送了大约50个GET请求.服务器是一个嵌入式服务器,位于一小块硬件上,资源非常有限.为了优化每个请求的性能,我配置了Alamofire.Manager的一个实例,如下所示:

let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.HTTPMaximumConnectionsPerHost = 2
configuration.timeoutIntervalForRequest = 30
let manager = Alamofire.Manager(configuration: configuration)

当我发送manager.request(...)个请求时,它们会以2对的形式发送(正如预期的那样,通过Charles HTTP Proxy进行判断).但奇怪的是,所有在第一次请求后30秒内未完成的请求都会因为超时而被取消(即使它们尚未发送).下面是一个展示这种行为的插图:

并发请求插图

这是一种预期行为吗?我如何确保请求在发送之前不会超时?

谢谢!

推荐答案

是的,这是预期的行为.一种解决方案是将请求封装在定制的异步NSOperation子类中,然后使用操作队列的maxConcurrentOperationCount来控制并发请求的数量,而不是HTTPMaximumConnectionsPerHost参数.

最初的AFNetworking在将请求包装到操作中方面做得很好,这使得它变得微不足道.但AFNetworking的NSURLSession实现从来没有做到这一点,阿拉莫菲尔也没有做到.


您可以轻松地将Request封装在NSOperation子类中.例如:

class NetworkOperation: AsynchronousOperation {

    // define properties to hold everything that you'll supply when you instantiate
    // this object and will be used when the request finally starts
    //
    // in this example, I'll keep track of (a) URL; and (b) closure to call when request is done

    private let urlString: String
    private var networkOperationCompletionHandler: ((_ responseObject: Any?, _ error: Error?) -> Void)?

    // we'll also keep track of the resulting request operation in case we need to cancel it later

    weak var request: Alamofire.Request?

    // define init method that captures all of the properties to be used when issuing the request

    init(urlString: String, networkOperationCompletionHandler: ((_ responseObject: Any?, _ error: Error?) -> Void)? = nil) {
        self.urlString = urlString
        self.networkOperationCompletionHandler = networkOperationCompletionHandler
        super.init()
    }

    // when the operation actually starts, this is the method that will be called

    override func main() {
        request = Alamofire.request(urlString, method: .get, parameters: ["foo" : "bar"])
            .responseJSON { response in
                // do whatever you want here; personally, I'll just all the completion handler that was passed to me in `init`

                self.networkOperationCompletionHandler?(response.result.value, response.result.error)
                self.networkOperationCompletionHandler = nil

                // now that I'm done, complete this operation

                self.completeOperation()
        }
    }

    // we'll also support canceling the request, in case we need it

    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 {
            // handle error here

            print("failed: \(error?.localizedDescription ?? "Unknown error")")
            return
        }

        // update UI to reflect the `responseObject` finished successfully

        print("responseObject=\(responseObject)")
    }
    queue.addOperation(operation)
}

这样,这些请求将受到maxConcurrentOperationCount的限制,我们不必担心任何请求超时..

这是一个示例AsynchronousOperation基类,它负责处理与异步/并发NSOperation子类关联的KVN:

//
//  AsynchronousOperation.swift
//
//  Created by Robert Ryan on 9/20/14.
//  Copyright (c) 2014 Robert Ryan. All rights reserved.
//

import Foundation

/// Asynchronous Operation base class
///
/// This class performs all of the necessary KVN of `isFinished` and
/// `isExecuting` for a concurrent `NSOperation` subclass. So, to developer
/// a concurrent NSOperation subclass, you instead subclass this class which:
///
/// - must override `main()` with the tasks that initiate the asynchronous task;
///
/// - must call `completeOperation()` function when the asynchronous task is done;
///
/// - optionally, periodically check `self.cancelled` status, performing any clean-up
///   necessary and then ensuring that `completeOperation()` is called; or
///   override `cancel` method, calling `super.cancel()` and then cleaning-up
///   and ensuring `completeOperation()` is called.

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")
        }
    }

    /// Complete the operation
    ///
    /// This will result in the appropriate KVN of isFinished and isExecuting

    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`")
    }
}

/*
 Abstract:
 An extension to `NSLocking` to simplify executing critical code.

 Adapted from Advanced NSOperations sample code in WWDC 2015 https://developer.apple.com/videos/play/wwdc2015/226/
 Adapted from https://developer.apple.com/sample-code/wwdc/2015/downloads/Advanced-NSOperations.zip
 */

import Foundation

extension NSLocking {

    /// Perform closure within lock.
    ///
    /// An extension to `NSLocking` to simplify executing critical code.
    ///
    /// - parameter block: The closure to be performed.

    func withCriticalScope<T>(block: () throws -> T) rethrows -> T {
        lock()
        defer { unlock() }
        return try block()
    }
}

这种模式还有其他可能的变化,但只要确保你(a)返回trueasynchronous;和(b)您发布必要的isFinishedisExecuting KVN,如Concurrency Programming Guide: Operation QueuesConfiguring Operations for Concurrent Execution部分所述.

Swift相关问答推荐

为什么不能使用actor作为AsyncSequence中的状态机类型?

JSON如何解码空对象

VisionOS发送通知

在解码字符串时需要帮助.

如何在HStack中均匀分布视图?

RealityKit如何获得两个相对大小相同的ModelEntity?

有没有一种方法可以迭代可编码的代码(例如,JSON解析中的每一项)?

SwiftUI正在初始化不带状态变量的绑定变量

try 在小部件内部读取核心数据的SwiftUI总是返回空吗?

如何获取嵌套数组中项的路径以修改数组?

我需要一些关于 SwiftUI 动画的帮助

如何使 onKeyPress 与 TextField 快速配合使用?

为什么无法在 Swift 中使用AVFoundation扫描 QRCode

SwiftUI:列表背景为空列表时为黑色

如何在 ZStack 中单独下移卡片?

Vapor, fluent 使用 PostgreSQL 保存/创建复杂模型

Swift中的分段错误

macOS 守护进程应该由Command Line ToolXcode 模板制作吗?

如何使用 Swift/iOS 为人类书写的笔画制作动画?

try 在解除分配时加载视图控制器的视图... UIAlertController